Receiving Jquery POST data in Express - javascript

Edit See the accepted answer below for the fix. I also had to remove the line contentType: 'appliction/json', from my POST request.
I'm trying to send a string to Node.js / Express, but req.body is undefined server-side.
Client jQuery:
$.post({
traditional: true,
url: '/matches',
contentType: 'appliction/json',
data: viewedProfiles,
dataType: 'json',
success: function(response){
Express:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post('/matches', isLoggedIn, function(req, res){
console.log(req.body) // this is undefined
var loadedProfiles = []
loadedProfiles.push(req.body.viewedProfiles)
console.log('loadedProfiles')
console.log(loadedProfiles)
I've tried:
not specifying 'dataType'
setting data: JSON.stringify(viewProfiles)
splitting the string into an array on the client, and then having jQuery stringify it
looking for req.params instead of req.body (clutching at straws)
I can see the XHR request in dev tools, and it contains the string I'm expecting.
What super obvious thing am I missing to send the data to Express?
Thanks.

Your server side code looks fine but you need to use $.ajax() rather than $.post() function because $.post() function send data into url (with url encoded). So your JQuery code would be
$.ajax({
url: '/matches',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"viewedProfiles": viewedProfiles}),
success: function(response){
I hope this will help you

I've configured an exact same setup. And code below works:
var profiles = { 'data' : 'hello' };
$.post({
traditional: true,
url: '/matches',
contentType: 'application/json',
data: JSON.stringify( profiles ),
dataType: 'json',
success: function(response){ console.log( response ); }
} );
My nodejs engine:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post( '/matches' , function(req, res){
console.log(req.body) // this outputs: { data: 'hello' }
} );
Btw, There is a typo where your contentType is, 'applicAtion/json'

Related

Javascript & Node.js - make a JSON request

in this Question I read that in node.js you can distinguish between html requests and json requests like so:
app.get('/route', function (req, res) {
if (req.is('json')) res.json(data);
else if (req.is('html')) res.render('view', {});
else ...
});
now my question is how do you make a request that is interpreted as json in node server?
cause I tried with $.ajax and $.getJson and typed in the browser and all were html requests.
this is my request
$.ajax({ type: 'GET', url: "/test", dataType:"json", success: function(data){log(data)}})
The req.is method checks the incoming request type by inspecting the Content-Type header therefore you need to make sure this header is set in the request before it's sent up e.g.
$.ajax({
type: 'GET',
url: '/route',
contentType: "application/json; charset=utf-8",
....
});
However, the Content-Type header is used to determine the format of the request body, not the response. It's recommended you use the Accept header instead to inform the server of what type of format is appropriate for the response e.g.
app.get('/route', function (req, res) {
if (req.accepts('html')) {
res.render('view', {});
} else if (req.accepts('json')) {
res.json(data);
} else {
...
}
});
Then on the client, you don't need to worry about the Content-header but rather the Accept header, and jQuery already provides a handy little method for that
$.getJSON('/route', function(data) {
...
});
Try setting the contentType parameter
$.ajax({
type: 'GET',
url: 'your_url',
data: {
test: "test"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
....
});
EDIT:
You can use the request Module
all you have to do is
var request = require('request');
var options = {
uri: 'your_server_side_url',
method: 'POST',
json: {
"data": "some_data"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.id) // Print the shortened url.
}
});
Check out that github link. May be that module will make your life easier

JQuery not posting to Express backend

I have a program that was working before and when I ran it today, the post seems to not be getting to the server. I added an alert to debug, and it runs successfully. Here is the JQuery code:
$(document).ready(function() {
$("#submit").click(function(d) {
d.preventDefault();
var data = {"message" : $("#theText").val()};
alert($("#theText").val());
$.ajax({
type: "POST",
url: "/post",
processData: false,
contentType: "application/json",
data: JSON.stringify(data),
dataType: text
});
});
});
It is being passed into an Express route that just looks like this:
app.post("/post", log, dc);
It does not show up on the logger at all, and even if I change it to something like this it still doesn't print:
app.post("/post", function(){
console.log("received post");
});
You are passing a named variable to dataType...should be a string like 'json' or 'text'. That is probably causing the primary error.

jQuery .ajax POST request has an empty body when received by Node

For some reason when I make an ajax post using jQuery, the body, as received by node is empty. Here is my ajax post:
jQuery
var formData = {
'order': order,
'words': 'words'
};
$.ajax({
type: 'post',
url: 'https://example.com/charge',
processData: false,
data: JSON.stringify(formData),
contentType: 'json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
And here is my node code:
Node
app.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', routes);
routes/index.js
router.post('/charge', function(req, res) {
console.log(req.body);
} //This always logs {}
I have no idea what I could be doing wrong here. My browser even shows a payload and the post request (the formData object) but node logs nothing. Any ideas?
Use ajax request like this:
$.ajax({
type: 'post',
url: 'https://example.com/charge',
data: formData,
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
Mine was not working too, but solved by using,
contentType: 'application/json',
data: JSON.stringify(formdata),
Check following api
By setting the processData option to false, the automatic conversion of data to strings is prevented.
If you want to use json type, processData must be setted true
Jquery processData
This may be a late reply, but please also note the JQuery ajax documentation:
Object must be Key/Value pairs.
This took me 2 hours (server received empty body) because I was trying to post a more 'complicated' object.

ERROR: bad URI when sending data as JSON with GET method to a Rails resource

Hello I'm performing a GET request on a RESTful Rails resource, like so:
function getGroups(category) {
$.ajax({
type: 'GET',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
success: function(data) {alert(data)},
contentType: "application/json",
dataType: 'json'
});
});
getGroups("own_groups");
The problem is that Webrick server errors out like this:
ERROR bad URI
`/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.
It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...
Update: adding code for POST request (where JSON.stringify is required)
function addGroup(name, description) {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
success: function(data) { alert("ok")},
contentType: "application/json",
dataType: 'json'
});
};
addGroup("nice group", "full of people");
Do not use JSON.stringify. Simply put:
data: {"access_token":"569669d8df0456", "category":category },
Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories