简体   繁体   中英

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.

您使用了Get方法。将其更改为Post方法

app.post('/search', function{});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM