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

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

Related

Ajax request send property path

I'm trying to send data to server.
My Ajax call:
$.ajax({
url: config.api.url,
type: config.api.method,
contentType: config.api.contentType, // application/x-www-form-urlencoded; charset=UTF-8
dataType: config.api.dataType, // JSON
data: config.api.dataType === 'GET' ? {} : JSON.parse(tmp),
headers: config.api.headers,
success: (response) => { onSuccess(response); },
error: (error) => { onError(error); }
});
My data:
{
sort: { name: 1 }
}
// I set name property by sort['name'] = 1; at js
But the server received:
{ 'sort[name]': 1 }
My nodejs server code:
exampleData = (req, res) => {
var sort = req.body.sort;
console.log(sort); // undefined
console.log(req.body); // { ..., 'sort[name]': 1 }
}
Chrome Form Data:
So, I can't read object correctly like an object sent from ajax request, something went wrong?
How can I fix it?
I hope you are using express.js. If yes then you need body parser middleware.
var app = require('express')(),
bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', function (req, res) {
console.log(req.body);
});

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

How to send a json object that holds a file in it to Nodejs?

I'm working on this simple Form application using Nodejs as my Server side. I'm able to receive the JSON object data sent by the Ajax call to Node. But my issue is that when I add a new property to my JSON object that will allow me to upload a file (data location: $('input[type=file]')[0].files) the server doesn't get it and it throws me an error.
So how can I attach a new property that holds a file value to my json object so my server can receive it? or do I need to change my Ajax call differently?
Here's my code:
script.js
$("form").submit( function() {
hideError();
submit = submitAnswers();
if(submit == true){
var jsonData = createJson();
$.ajax({
url: '/form',
type: 'POST',
dataType: 'json',
data: jsonData,
// enctype: 'multipart/form-data',
// //contentType: 'application/json',
error: function(err){
console.log(err);
showError(err.responseText);
}
});
}
});
function createJson(){
var answers = $("form[name = quizForm] input[type=radio]:checked")
var results = {
authority: answers[0].value == 'a',
sharing: answers[1].value == 'a',
accuracy: answers[2].value == 'a',
quality: answers[3].value == 'a',
complete: answers[4].value == 'a',
format: answers[5].value == 'a',
type: answers[6].value == 'a',
ownership: answers[7].value == 'a'
datalocation: $('input[type=file]')[0].files
}
return results;
}
Server Code
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.sendfile('./public/html/form.html');
});
router.post('/', function(req, res, next) {
/*This verifies that json data was sent to Server after being executed by the Ajax call*/
console.log('Request received: ');
console.log(req.body) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
console.log('\nRequest recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url
res.end('callback(\'{\"msg\": \"OK\"}\')');

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

Categories

Resources