Asynchronous POST shows Unexpected token n - javascript

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?

Related

nodejs server not receiving any parameters from POST request [duplicate]

This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 5 years ago.
server.js:
var express = require('express');
var app = express();
loggedIn = {};
app.use('/',express.static('www')); // static files
app.listen(8080, function () {
console.log('Port 8080!');
});
app.get('/user', function(req, res) {
if (typeof req.param('user') != 'undefined') {
user = req.param('user');
res.status(200).send('Works');
}
});
app.post('/user', function(req, res) {
user = req.param('user');
if (typeof users[user] != 'undefined') {
return res.status(405).send('Access Forbidden');
} else {
loggedIn[user] = "";
res.status(201).send('New User');
}
}
});
client.js requests:
$.ajax({
method: "GET",
url: "/user",
data: {"user" : user},
dataType: "application/json",
success: function(data) {
// success
},
error: function() {
// error case
}
});
$.ajax({
method: "POST",
url: "/user",
data: {"user" : user},
dataType: "application/json",
success: function(data) {
// success
},
error: function() {
// error case
}
});
Even though the GET request works exactly as expected and passes the parameter here, for some reason, the post request doesn't. In firebug, I notice the POST request receives no parameters whatsoever (POST user) while GET request does (GET user?user=XYZ). I am really at a loss right now.
You have to tell your express app to parse the request body
app.use(express.bodyParser());
for express 4+
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
For reference goto https://expressjs.com/en/4x/api.html#req and look at the section titled req.body

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)
});

php to node.js ajax sending does not give response

I was trying to post some data from my php page to my node.js server.and I want to get the response from it.
This is the ajax code which I was sending from my php page which is currently executing on the apache server
function encryptCode()
{
var value = document.getElementById("code").value;
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: JSON.stringify(value),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
and I just want to receive it in my node.js page by this code
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(data);
/*this.getContent(function() {
// var v = new View(res, 'place');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(self.content));
});*/
// console.log("go to hell");
},
});
This is a controller of my express.js,which I have redirected from my app.js page with this code
app.all('/insertUser', attachDB, function(req, res, next) {
insertUser.run( req, res, next);
});
will somebody please help me out in the console.log I am getting {} .....
First test is it problem with the frontend.
function encryptCode()
{
var value = document.getElementById("code").value;
console.log(value);
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: {"user":value},
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
You should set json body parser in your express app
var app = express();
bodyParser = require('body-parser');
app.use(bodyParser.json());
where did you declare data variable. In node.js the data sent through ajax request is available at req.body
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(req.body);
// console.log(req.body.user);
},
});

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)

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

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.

Categories

Resources