req.body is always empty. I'm not sure what I'm doing wrong? I tried adding content-type headers as json but that didn't do anything either. Can someone lead me in the correct direction please? Thank you
EDIT: just for clarification purposes, my Angular frontend hits the backend function successfully, but req.body is empty. If I understand everything correctly, if I'm using the 'body-parser' library, it should be passed in through post through 'req.body'. I'm just not seeing that though and I'm not sure why.
EDIT2: I have the body parser code in my app.js but the backend routing in a index.js file, does that have anything to do with it?
EDIT3: app.js http://pastebin.com/9vNgf0Nd
index.js http://pastebin.com/icLa3e2X
ANGULAR FRONTEND
service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {'Content-Type': 'application/json'}
});
}
BACKEND (app.js)
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
BACKEND (index.js)
var express = require('express');
var router = express.Router();
router.post('/register', function(req, res) {
console.log(req.body);
};
Please remove this line
app.use(bodyParser.urlencoded({ extended: true }))
Also,
app.use(bodyParser.json());
have to be called before app.use('/', routes);
And make sure to add Content-Type: application/json to the request header
What happens if you add the content type?
service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {
'Content-Type': 'application/json'
}
});
}
Try this
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/register', function(req, res) {
console.log(req.body);
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
and then execute this from prompt:
$ curl localhost:8081/register -v --data "{\"name\":\"test\",\"password\":\"hello\"}" --header "Content-Type: application/json"
this works for me!
There is nothing wrong in the UI code. Not sure what is router so you may try this or post the code for router.
Try this (this works for me) or you can also use your router:
app.post('/register', function (req, res) {
console.log(req.body);
res.send('welcome, ' + req.body.account.username)
});
You are missing:
var app = express();
app.use(router);
If you want to user routers refers to following example:
UPDATE with full code:
var express = require('express');
var router = express.Router();
var app = express();
app.use(router);
router.post('/register', function(req, res) {
console.log(req.body);
};
app.route('/register')
.post(function (req, res) {
console.log(req.body);
res.send('welcome, ' + req.body.account.username)
})
Related
In my app I have a code from official docs, except one difference: I send xsrfToken in response to POST request, not GET.
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
var app = express()
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.post('/getCsrfToken', /*csrfProtection,*/ function (req, res) {
// check credentials from request.body
// and then
res.render('send', { csrfToken: req.csrfToken() }) //EXCEPTION: csrfToken is not a function
})
app.post('/process', parseForm, csrfProtection, function (req, res) {
res.send('data is being processed')
})
I'm facing the egg-hen problem: if I enable csrfProtection, I cannot get into the endpoint's code without the token, but if I disable it, req.csrfToken becomes undefined.
I need the gerCsrfToken endpoint to be POST, because I don't want to expose password as url parameter.
Question was answered by csurf maintainer, thanks for a quick response!
https://github.com/expressjs/csurf/issues/133
The (tricky) solution is to ignore POST method for this particular endpoint
app.post('/authenticate', csrf({ cookie: true, ignoreMethods: ['POST'] }), function (req, res) {
I am beginner use React Js and Node Js, I get a problem, I cannot post my data from React Js to Node Js, I have been looking for the way but failed all, I don't know why.
This is my complete code.
This is my react file 'member.js', run on port 3000 (http://localhost:3000/member).
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Member extends Component {
constructor() {
super();
this.state = { player: {} };
}
handleSubmit(e) {
e.preventDefault();
fetch('http://localhost:4000/player', {
mode: 'no-cors',
method: 'post',
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify({
number: 123,
name: "John",
position: "Andrew"
})
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
}
render() {
return (
<div className="member-page">
<form>
<input type="submit" onClick={this.handleSubmit.bind(this)} />
</form>
</div>
)
}
}
export default Member;
and this is my node file 'player.js', run on port 4000 (http://localhost:4000/player).
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
I don't know where I do a mistake, please anyone correct my code either member.js or player.js.
Thank you very much for all the help.
I agree with #robertklep. I think problem is in var player = req.body;
Try:
Install body-parser npm package
npm i -S body-parser
Configure body-parser
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//enable CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', (req, res) => {
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, (error, results, fields) => {
if (error) throw error;
// Neat!
});
res.send('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
var router = express.Router();
router.use( bodyParser.json() ); // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(5000, () => {
console.log('Example app listening on port 5000!')
})
app.use('/', router);
Try to Configure your node server like this
First install body-parser using :
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
If you are passing string data then use
app.use(bodyParser.text());
Otherwise if you are passing data as Json then use
app.use(bodyParser.Json());
It should work in your case.
I'm using Express router functions to handle some POST requests.
Client.js
let data = {
endpoint: "Blah Blah";
};
return fetch('/api/get-preferences/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
Server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
class HTTPServer {
constructor(credentials, app) {
this.app = app;
this.specifyRoutes();
}
specifyRoutes() {
this.router = express.Router();
this.router.use((req, res, next) => this.jwtVerify(req, res, next));
this.app.use('/api', this.router);
this.router.post('/get-preferences', this.getPref);
}
jwtVerify(req, res, next) {
console.log(req.body); // This prints "undefined".
next();
}
}
I can't access the data that I sent from the client side on the server side in the jwtVerify function and once this is fixed, I would like to pass that data to the getPref function in the /get-preferences route.
Two issues here. First, update:
this.app.use(bodyParser.json());
Second:
this.app.use('/api', this.router);
Sample 'Advanced REST Client' Request
I'm using Postman and Advanced REST client to create a basic POST request for the following code -
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//app.listen(6666);
http.createServer(function (req, res) {
h2s(req, res);
}).listen(6666, '127.0.0.1');
console.log('Server running at http://127.0.0.1:6666/');
module.exports = function h2s(req, res) {
console.log("inside h2s");
app.use(function (req, res) {
console.log("req.body : " + req.body);
res.send("OK");
});
}
But, when I debug, I find that req.body is missing in the "req object tree". What's more strange is all the changes that I make to req.headers are available in the req object tree.
Looks like I seem to be making a trivial mistake, but I'm unable to figure it out. Been trouble-shooting for an hour or so but no luck!
Can anyone of you figure out why req.body seems to be missing from the req object tree?
Will be of great help to me. Thanks!
It looks like you have several issues in your code:
instead of
http.createServer(function (req, res) {
h2s(req, res);
}).listen(6666, '127.0.0.1');
console.log('Server running at http://127.0.0.1:6666/');
module.exports = function h2s(req, res) {
console.log("inside h2s");
app.use(function (req, res) {
console.log("req.body : " + req.body);
res.send("OK");
});
}
For creating the server, try
http.createServer(app).listen(8000, '127.0.0.1'); //using http
Or (using express directly)
app.listen(8000,function(){
console.log('Server running at http://127.0.0.1:8000/');
});
Then register an handler function for your requests, there you can access req.body
app.use(function (req, res) {
console.log("req.body : " + req.body);
res.send("OK");
});
Dear u set body parser Url Encoding to true
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: true
}));
and check by printing the req.body, it work for me and might for u also
the req.body can be accessed also when
content-type:"application/x-www-form-urlencoded"
read this
In your case , your content-type is application/json"
so try changing the content-type to "application/x-www-form-urlencoded"
also url encode the parameters while sending to the server from JS
also solution can be
// fire request
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(requestData)
}, ...
Declaration:
var express = require('express');
var router = express.Router();
Route.js: Post call here
router.route('/signup')
.post(function (req, res) {
console.log('post signup called', req.body);
res.json({message: 'signup'});
});
module.exports = router;
The req.body is always undefined. I am able to print them console inside ajax call. I don't understand req.body is undefined. What am I missing?
Ajax post data sent like:
$.ajax({
url: '/signup',
type: 'POST',
data: params,
success: function (res) {
console.log('res', res);
},
error: function (err) {
console.log('err', err);
}
});
server js: Already using body-parser here
var express = require("express");
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var request = require("request");
var router = require('./app/routes/route.js');
var functions = require('./app/functions/functions.js');
var http = require('http');
var https = require('https');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var model = require('./app/model/model.js');
app.use('/', express.static(__dirname + '/public_html'));
app.use('/', router);
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false }));
Your requests won't be passed through body-parser because you're declaring it after the router (Express passes requests through middleware and routes in order of declaration; if a request can be handled by router, it won't be passed through the body-parser middleware anymore):
app.use('/', express.static(__dirname + '/public_html'));
app.use('/', router);
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false }));
If you move body-parser to the front, it should work better:
app.use('/', express.static(__dirname + '/public_html'));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false }));
app.use('/', router);
You have to use body-parser
https://www.npmjs.com/package/body-parser
express.use(bodyParser.json());