Home > other >  Body is empty, only from post in React. Postman works
Body is empty, only from post in React. Postman works

Time:09-29

I have a React front-end with a Prisma (Express based) Node.js back-end.

I can make Post request via postman (content type: x-www-form-urlencoded). When I try to post via my front-end however, I can not seem to get my body object to contain any data.

My React Axios post function:

async function acceptCreateTask() {
const createTaskFormData = new FormData();

createTaskFormData.append("title", formValue.title);
createTaskFormData.append("category", formValue.category);
createTaskFormData.append("discription", formValue.discription);

try {
  const response = await axios({
    method: "post",
    url: "http://localhost:3001/task",
    data: createTaskFormData,
    headers: { "content-type": "application/x-www-form-urlencoded" },
  }).then((res) => {
    //
  });
} catch (error) {
       //
   }  
}

Prisma Express function

const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

var cors = require("cors");
var express = require("express");
var app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//create a task
app.post("/task", async (req, res) => {
  console.log(req.body);

  const taskTitle = req.body.title;
  const taskCategory = req.body.category;
  const taskDiscription = req.body.discription;

  if (!req.body || !taskTitle || !taskCategory || !taskDiscription) {
    return res
      .status(400)
      .json({ message: "Title, categoy or discription is missing" });
  }

  try {
    const message = "Task created successfully";

    await prisma.task.create({
      data: {
        title: taskTitle,
        category: taskCategory,
        discription: taskDiscription,
      },
    });
    return res.json({ message });
  } catch (e) {
    return res.status(500).json({ message: "something went wrong" });
  }
});

CodePudding user response:

You're sending form data. You should use URLSearchParams to send URL-encoded data.

Here an example using a mirror API which just mirrors the request that was sent. You should have a look at the Body section.

(async () => {
  const response = await fetch('https://apichallenges.herokuapp.com/mirror/request', {
    method: 'POST',
    body: new URLSearchParams({
      'userName': '[email protected]',
      'password': 'Password!',
      'grant_type': 'password'
    })
  });
  console.log(`HTTP status code: ${response.status}`);
  console.log(await response.text());
 })();
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }

By the way: It's always useful to inspect the HTTP status code for those kind of errors as this will give an indication what went wrong.

This does also work with Axios. Please see Axios documentation

(async() => {
  const data = new URLSearchParams({
    'userName': '[email protected]',
    'password': 'Password!',
    'grant_type': 'password'
  });
  const response = await axios.post('https://apichallenges.herokuapp.com/mirror/request', data)
  console.log(`HTTP status code: ${response.status}`);
  console.log(response.data.messageDetails);
})();
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  • Related