Having a problem with something that should be relatively simple. I am sending a POST request with JSON DATA as follows :
curl -H "Content-Type : application/json" -X POST -d '{"searchbar":"cat"}' http://someurl.com/public/search
Within my application I have a route ... under '/routes' I have set the bodyParser as follows:
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
In the route I have var searchbar = req.body.searchbar
However the variable searchbar is always undefined.
I can see the data in the body as follows:
{ '{searchbar:cat}': '' }
Obviously the data is either not being sent correctly by the curl (so my curl is incorrect) or the data is not being parsed by the bodyParser. Can anyone help ?
EDIT : routes/index.js
var express = require('express');
var bodyParser = require('body-parser');
var moment = require('moment');
var fs = require('fs');
var router = express.Router();
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.all('*',function(req,res,next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
next();
});
router.post('/public/search/', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
var searchbar = req.body.searchbar;
console.log("Searchbar is : " + searchbar);
console.log("body is : " + require('util').inspect(req.body, false, null));
});
modeul.exports = router;
UPDATE:
I used postman (chrome plugin) and managed to send and parse the data - there must be an issue with CURL in this instance ...
Have the data inside quotes as follows:
curl -H "Content-Type : application/json" -X POST -d '{"searchbar":"cat"}' http://someurl.com/public/search
In your case its not json its s string , so its undefined.
EDIT:
Instead of this:
router.use(bodyParser.json());
Try for this:
router.use(express.bodyParser());
I finally solved this "mystery"
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"searchbar":"cats"}' http://someurl/public/search
Both the Accept and Content-Type headers were needed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.