Passing array from POSTMAN and AJAX is different when received by ExpressJS - ajax

I am new to Express but not in programming. I am trying to pass an array via ajax from my frontend to express. On my postman, this is the array I am sending:
{
"userIds": ["xxxxxxxxxxxxxxxxxx"],
"type": "user"
}
and express is receiving req.body as:
{
userIds: [ 'xxxxxxxxxxxxxxxxxx' ],
type: 'user'
}
When I do this in Ajax:
data = {
userIds: ["xxxxxxxxxxxxxxxxxx"],
type: "user",
};
$.ajax({
type: "POST",
url: url,
headers: headerParams,
data: data,
success: function (room) {
console.log("room", room);
},
error: function (error) {
console.log("error", error);
},
});
Express is receiving:
[Object: null prototype] {
'userIds[]': 'xxxxxxxxxxxxxxxxxx',
type: 'user'
}
What am I doing wrong here? Or how should I mutate my req.body to get the desired output?
Note: I cannot do req.body.Foreach since it is saying forEach is not a function.
Note 2: req.body.userIds returns undefined

My best guess, Middleware body-parser to your rescue.
You can then access it as req.body.userIds, which will be an Array.

Related

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

Extjs 5 ajax PUT and DELETE methods throw 403 errors (csrf token included)

I am building a web application with django-rest-framework and extjs5.
Obviously i faced problems with django's csrf token, which i had to inlude in Extjs's Ajax requests.
But while i implemented POST method successfully, it seems that my implementation doesn't work for PUT and DELETE method.
My POST method code:
onSaveRecordBtnClick: function(){
Job_Name = this.lookupReference('Job_Name').getValue();
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/',
method: "POST",
params: {
Job_Name: Job_Name,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Submission Successfull');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
This works perfectly, but when i try PUT or DELETE method i keep getting:
Request Method:DELETE
Status Code:403 FORBIDDEN
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
My DELETE method:
onJobDblClick : function(grid, record, index, eOpts) {
var job_id = record.id;
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/' + job_id + '/',
method: "DELETE",
params: {
'id': job_id,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Deleted Successfully');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
My job model is:
Ext.define('MyApp.model.Job', {
extend: 'MyApp.model.Base',
fields: [
{ name: 'id', type: 'int' },
{ name: 'Job_Name', type: 'string' },
],
proxy: {
type: 'rest',
url: '/jobs_api/job/',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
I don't know why this is happening. Please help!!

How to write unit test to embeded ajax requests?

I have the handleDownload method which starts a file download. The function posts to the backend, which gives back a response, based on that a new request posts to the server where the files are. I saw that I can use mockjax to mock the requests, but how to handle the different paths like success, error, etc. How should I know which response triggers which path (success,error, complete, ...). What would be a great startegy to test the handleDownload function, and how? For mocking I use Sinon.js I don't have a really deep understanding yet. I should also check either the handleDownloadFinal function is called.
handleDownload: function(data, url) {
$.ajax({
type: "POST",
url: url,
data: {},
success: function(response) {
if (response.success) {
var start_token = response.token;
$.ajax({
type: start_token.method,
url: start_token.url,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', start_token.header);
},
success: function(start_response) {
handleDownloadFinal(start_response.status_token);
},
error: function(start_response) {
$.ajax({
type: "POST",
url: url + 'proxy/',
success: function(fallback_response) {
if (fallback_response.success) {
handleDownloadFinal(fallback_response.status_token, true, fallback_response.job_uuid);
} else {
errorDownload(response.error);
}
},
error: function(fallback_response) {
// Now this is some real error
generalErrorDownload();
},
dataType: 'json'
});
},
dataType: 'json',
xhrFields: {
withCredentials: true
}
});
} else {
errorDownload(response.error);
}
},
error: function(response) {
generalErrorDownload();
},
complete: function() {
},
dataType: "json"
});
}
You should use the fake server coming with sinon.
before(function(){
//create the server
this.server = sinon.fakeServer.create();
// let the server automatically respond for every request
server.autoRespond = true;
})
it('test something', function(){
//let the server respond for specific url with 200-ok
this.server.respondWith("POST", "/some/article/comments.json", [200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]']);
})
As you have a bunch of requests and you have to check all combinations I would suggest to have helper function for every request fail success so you could test the cases like this:
function letFirstRequestSucceed() {
this.server.respondWith("POST", "urlForFirstRequest", [200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]']);
}
function letSecondRequestFail() {
this.server.respondWith("POST", "urlForSecondRequest", [404, {
"Content-Type": "application/json"
}, '{error: "some error message"}');
}
function letThirdRequestFail() {
this.server.respondWith("POST", "urlForThirdRequest", [404, {
"Content-Type": "application/json"
}, '{error: "some error message"}');
}
it("should to something when the second and third request fails", function () {
sinon.spy(window, 'generalErrorDownload');
letFirstRequestSucceed();
letSecondRequestFail();
letThirdRequestFail();
handleDownload('someDate', 'aUrl');
expect(generalErrorDownload)
})
Btw you should think about to refactor you code using jquerys deferred which is supported by api ajax calls, this would make your could much more readable.

How to make an AJAX request to jsFiddle's echo api using Ext.Ajax?

I'm trying to make a simple AJAX call to jsFiddle's JSON echo api using Ext.Ajax. It makes the request successfully, but the object returned is empty, not the JSON object I send (which it should be).
Code:
Ext.Ajax.request({
url: '/echo/json/',
jsonData: { foo: 'bar' },
success: function(resp) {
console.log('success!');
console.log(Ext.decode(resp.responseText)); //empty object..? why?
},
failure: function(resp) {
console.log('failure!');
},
});
Fiddle: http://jsfiddle.net/nANE7/
How come the response is just an empty object? Where's the foobar JSON information that it's meant to echo back?
Try this:
Ext.Ajax.request({
url: '/echo/json/',
params: {
json: Ext.encode(
{
param1:'bar'
}
)
},
success: function(resp) {
console.log('success!');
console.log( resp );
console.log(Ext.decode(resp.responseText)); //empty object..? why?
},
failure: function(resp) {
console.log('failure!');
},
});

AJAX : How to get info about permission reject

I have an ASP.NET MVC application, where I call method by AJAX:
$.ajax({
dataType: 'json',
url: "/Admin/AllowVideoUpload",
type: "POST",
data: { val: val },
error: function () {
alert('Error');
}
});
if success - nothing happens on client side, if error - get 'Error' message. But error can be by different reasons - problem inside "AllowVideoUpload" method or user lost his credentials (AdminController has attribute 'Authorize(Roles = "Admin")'). I want to differ these 2 types of error. How to do it?
Those are your application level errors. So it should be handled in the success handler.
You may return json from your action method which has a Status /Error code/Message element where you mention what is the error reason.
Sample Json for Error
{
"Status": "Failed",
"Message": "Authentication Failed"
}
Sample Json for Success
{
"Status": "Success",
"Message": "Successfully Updated"
}
Read the jSon and then you can decide what to do next.may be show message to user
$.ajax({
dataType: 'json',
url: "/Admin/AllowVideoUpload",
type: "POST",
data: { val: val },
success:function(data){
if(data.Status=="Success")
{
//operation success. do whatever
}
else if(data.Status=="Failed")
{
alert(data.Message);
}
},
error: function () {
alert('Error');
}
});

Resources