简体   繁体   中英

Axios post sending body but body is undefined with fetch and Postman

I'm not able to send a post body with fetch or Postman, but I can send the body with Axios.

Axios returns: User name = Fred, password is Flintstone

But Postman and fetch both return User name = undefined, password is undefined

How can I get the post body with fetch and postman?

Server File

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

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post("/login", (req, res) => {
  var user_name = req.body.user;
  var password = req.body.password;
  console.log("User name = " + user_name + ", password is " + password);
  res.end("yes");
});

app.listen(3000, () => {
  console.log("Started on PORT 3000");
});

Axios

axios.post("http://localhost:3000/login", {
  user: "Fred",
  password: "Flintstone",
});

Fetch (client side)

fetch("http://localhost:3000/login", {
  method: "POST",
  body: JSON.stringify({ user: "Fred", password: "Flintstone" }),
  mode: "no-cors",
});

Postman

在此处输入图片说明

In Postman you are trying to send JSON data as a text. Change the type of data sent from Text (what you have now) to JSON in Postman .

在此处输入图片说明

Also as a suggestion, you should leave 1 bodyParser in your server file

For fetch() I recommend you to take a look at this question, some adjustments must be made Fetch: POST json data

fetch doesn't default to posting JSON, which is why you had to encode the body explicitly. You also need to tell the server that you are sending JSON.

You can't do that without permission from CORS, so you must not set the mode to no-cors .

const headers = new Headers();
headers.append("Content-Type", "application/json");

fetch("http://localhost:3000/login", {
  method: "POST",
  body: JSON.stringify({ user: "Fred", password: "Flintstone" }),
  headers
});

The problem with Postman is probably the same (but not visible in the UI screenshot): You need to set the Content-Type header.

Try this:

app.post("/login", (req, res) => {
  var user_name = req.body.user;
  var password = req.body.password;
  console.log("User name = " + user_name + ", password is " + password);
  res.json({ "user name": user_name, "password": password });
});

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