简体   繁体   中英

axios post request from frontend not recieving in node js backend

I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.

Here is the code

node js

var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
  console.log("Got a GET request for the homepage");
  res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
  console.log(req.body);

  res.send("Hello GET");
});

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);
});

frontend

axios.post("http://localhost:8081/", { body: "dan" })
  .then((e) => console.log(e))

The response is an empty object.

What should I do?

You should use bodyParser.json(), to get the data sent in req.body.

var bodyParser = require('body-parser');
app.use(bodyParser.json());

By default your axios code:

axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))

will send the body of the POST request as JSON. Quoted directly from the axios doc .

By default, axios serializes JavaScript objects to JSON

So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.

 app.post('/', express.json(), function (req, res) {
   console.log(req.body);
   res.send('Hello POST');
 });

Note, there is no need to separately load the body-parser module as it is built-in to Express.


Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.

我们应该在使用中间件访问它之前解析请求体,方法如下

app.use(bodyParser.json());

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