Search code examples
javascriptnode.jsaxiosfetchpostman

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

enter image description here


Solution

  • 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.