Accessing JSON string parsed by Node's Express bodyParser() - javascript

Question: What object is the JSON parsed to?
I'm successfully sending a JSON string to the server, but I haven't been able to access the object.
Client script, sending the JSON:
var loginCredentials= {
"username":creds.username,
"password":creds.password };
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
dataType: "json"
});
Login listener, waiting for and supposedly parsing the JSON:
function listen(){
app.use(express.bodyParser());
app.post('/login', function(req, res) {
var util = require('util');
console.log(util.inspect(req.body, false, null));
console.log(req.body.username);
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
Which logs:
Server running at http://127.0.0.1:8080/
{ '{"username":"username1","password":"badpassword"}': '' }
undefined
So it looks like my JSON is parsed right, but I'm trying to access it via req.body.username and it isn't stored there.

The bodyParser doesn't know that you're sending JSON. It assumes the body to be standard www-form-urlencoded, and therefore parses all of it as a single key.
Instead, send the proper content-type with your request:
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
contentType : 'application/json',
dataType: "json" // response type
});
However, as mentioned in Do Not Use bodyParser with Express.js, you might just use the express.json() middleware only.

Related

Node.js with express.js returns 500 to ajax call

I have a cordova project where I do the following request.
$("#asd").on("click",function(){
var data = {};
data.title = "title";
data.message = "message";
$.ajax('127.0.0.1:3000/register',
{
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function() { console.log('success');},
error : function() { console.log('error');}
});
});
Server side code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/register', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(3000);
But I get Internal Server Error 500 when I send the request. If I make a request simply by an html form or curl it just works fine.
What might be the cause of this?
$.ajax({
url:'/register', //or 'localhost:3000/register'
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function() { console.log('success');},
error : function() { console.log('error');}
});
Also you are required to use cors()
var cors = require('cors')
var app = express();
app.use(cors());
Also: https://enable-cors.org/server_expressjs.html
If it's related to the CORS, then you need to allow CORS on the server wich serves static via adding the following HTTP header:
Access-Control-Allow-Origin: http://127.0.0.1:3000
Here is the example for Express (they put a wildcard * instead of http://127.0.0.1:3000).
Try JSON.stringify() in response
res.send(JSON.stringify(req.body));

AngularJS http post not working with node server

I have this code in my node backend server:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
And this is the api i.e. i want to call:
router.post('/update/:_id', function(req, res, next) {
console.log("req.body:" + req.body);
}
This is my post request through angular 1:
var data = {something: "something"}
var url = 'http://localhost:8081/update/5982168b399ccf32ad75ce2e';
$http({
withCredentials: false,
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
})
.then(function (response) {
if (response.data) {
console.log("Post Data Submitted Successfully!");
}
}, function (response) {
console.log("Error status: " + response.status)
});
I am using Angular 1.6.1 version.
I have tried everything and looked through countless posts but none helped me. I can see the body going through. But i got undefined req.body in the node side backend.
Any help would be appreciated.
Thanks.
it could be the
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
your data is in JSON format, not x-www-form-urlencoded
{something: "something"}
you could try this
headers: {'Content-Type': 'application/json'}
by default you send JSON data in $http POST, so you may not need the header
just take it out and try
===============================================================
also, your data may not be in valid format
JS does not know what something is, it's not a variable right?
you have to make it a string, even if its the key of a { "key": "value" } pair
you could try this if above doesn't work
{
"something": "something"
}
to verify your JSON
https://jsonlint.com/
You need to stringify the data, and change the content type as was already said:
var data = {something: "something"}
var url = 'http://localhost:8081/update/5982168b399ccf32ad75ce2e';
$http({
withCredentials: false,
method: 'POST',
url: url,
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(data)
})
You should in addition make sure that you can make a POST to that url using Postman and that the body is received to discart a problem in the server. On a side note, consider using Angular Resource.

AngularJS don't send data to NodeJS server

Im new with NodeJS and Im trying to send data to server with Angular
$scope.logearse = function () {
$http({
method: "POST",
url: "http://localhost:8888/login",
data: $scope.usuario
}).then(function successCallback(response){
console.log(response)
}, function errorCallback(error){
alert("No se han podido enviar los datos")
})
}
But in the server when I try to receipt the request is always {}
http.createServer(function(peticion, respuesta){
console.log(peticion.url)
console.log(peticion)
// We begin with "login"
if (peticion.url == "/login") {
console.log("Inside of Login)
var datosUsuarioLogin = '';
peticion.addListener("data", function(chunk) {
datosUsuarioLogin += chunk;
// function called when a new chunk of data is recibed
});
peticion.addListener("end", function() {
// When the data is recibed is transformed in JSON
var datosUsuarioLoginObjeto = querystring.parse(datosUsuarioLogin);
recuperarDatos(datosUsuarioLoginObjeto, respuesta);
console.log(datosUsuarioLoginObjeto) //return {}
});
//End of LOGIN "if"
}
}).listen(8888)
The thing is the same code works if I use a form with a regular submit but no if I try to use the $http of ANGULAR.
I try to use "params" instead of "data" but "params" transform the data in the URL and the code dont works.
You need to use bodyParser to parse the request body and place the result in request.body of route.
app.use(express.bodyParser());
And the request:
$http({
method: "POST",
url: "http://localhost:8888/login",
contentType: "application/json",
data: $scope.usuario // if usuario is not a valid json, you could to use JSON.stringify($scope.usuario);
Ok, after a lot of time trying finnaly I use Express but the version of Express I use dont allow simply bodyParser I need to install the body parser middleware
Link to body-parser
And the code
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
app.post('/', jsonParser, function (request, response) {
response.send(request.body)
});

Asynchronous POST shows Unexpected token n

I am posting data via jQuery $.ajax() call like so:
var data = {};
data.name = $("#name").val();
data.email = $("#email").val();
data.message = $("#message").val();
$.ajax({
type: "POST",
url: "http://myHost/contact/sendEmail",
data: data,
contentType: "application/json",
dataType: "json",
success: function (data) {
console.log("success");
}
});
Which is then getting routed by contactRoutes.js:
contactRouter.route("/sendEmail").post(contactController.sendEmail);
To a controller which is supposed to pull the body of the request to then make an API call and send the email message.
sendEmail:
var sendEmail = function(req, res) {
var payload = {
to: req.body.email,
from: "noReply#test.com",
subject: req.body.name,
text: req.body.message
};
...Omitted for brevity
};
The error I continue to receive is SyntaxError: Unexpected token n in the body-parser module. I have app.js setup like this:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
I'm lost as to where to look. I've examined my JSON object and it appears correct, but obviously I'm missing something. Anyone have any suggestions? Also, how can I be sure that contactRoutes.js is picking up the content passed in data?

How to get data from jQuery ajax post with ExpressJS

Hi so I have a jquery post data that i'm sending:
$.ajax({
type: "POST",
url: app.config.backend_2 + '/notifications/usernames',
data: data,
contentType: 'application/javascript',
dataType: 'json',
success: function (result) {
console.log(result);
}
});
and this is my express receiver:
exports.save_usernames_for_notifications = function (req, res, next) {
var start = function () {
console.log(req);
};
start();
};
What do I do to get the data from the ajax to log it in the save_username_for_notifications function?
You need a body parser middleware in your expressjs application to parse your JSON req object
https://www.npmjs.com/package/body-parser
To configure it, you need this code
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // this is used for parsing the JSON object from POST
Then to get your data in your express application just do this
console.log(req.body.data)

Categories

Resources