Wednesday 7 June 2017

body-parser request.body is empty

I use axios.get() send data to server nodejs, i use request.body to use but request.body return {} for me.

in server.js file

const express = require('express');
const bodyParser = require('body-parser');
const app = express();


const setting = {
  port : 20101
}

app.set('port', (process.env.PORT || setting.port));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function(req, res, next){
  res.setHeader('Access-Control-Allow-Origin','*');
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

app.get('/search', function(req, res){
   if(!req.body) return res.sendStatus(400);
   console.log(req.body, ' <--- req.body'); // return {} <--- req.body
});


app.listen(setting.port, function() {
   console.log('listening on port : ' + setting.port);
});

and api file

 axios.get(apiPath('/search'),{
    keyword
  })
  .then(function(response){
    console.log(response, '<--- response');
  })
  .catch(function(error){
    console.log(error, '<--- error');
  })

Please suggest how I should solve the problem.



via wit_peter

No comments:

Post a Comment