1

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

enter image description here

Dashiell Rose Bark-Huss
  • 2,173
  • 3
  • 28
  • 48

3 Answers3

2

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.

enter image description here

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

Runsis
  • 831
  • 9
  • 19
2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-2

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