Reputation: 2624
Express -v : 4.13.3
Superagent -v : 1.4
function to send the POST request from the front-end of my app:
search: () => {
request.post('/api/search')
.set('Content-Type', 'application/json')
.send({hello: 'hello w'})
.end((err, response) => {
if (err) return console.error(err);
serveractions.receiveTest(response);
});
}
my express router file:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({extended: false}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
The request is successfully being sent and received by the router, but req.body is always empty even though I am doing .send({hello: 'hello w'})
with Superagent. What do I need to change in order to correctly send the json object and receive it in my router?
Upvotes: 2
Views: 5732
Reputation: 2624
I figured out the answer:
I changed my router file to:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
And my request method to:
searchRequest : (data) => {
request
.post('/api/search')
.send({ searchTerm : data })
.end((err, res) => {
if (err) console.log(err);
console.log(res);
})
}
Upvotes: 6