'400 bad request in post request from client side

I am building an app using nodejs, react, postgresql.

server.js

const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");

//middleware
app.use(cors());
app.use(express.json());


app.post("/todos",async (req,res)=>{
    try {
        const {description} =  req.body;
        const newStudent = await pool.query(
            "INSERT INTO todo (description) VALUES($1) RETURNING *",
            [description]
        );
        res.json(newStudent.rows[0]);
    } catch (err) {
        console.error(err.message);
    }
})

in reactcomponent.js

try {
      const body = values.firstName;
      const response = await fetch("http://localhost:5000/todos",{
        method: "POST",
        headers: {"Content-Type" : "application/json"},
        body: JSON.stringify(body)
      });
      console.log(response);
    } catch (error) {
      console.error(error.message);
    }

here value.firstName is something that is taken from form input. and create database table sql command -

CREATE TABLE todo(
todo_id SERIAL PRIMARY KEY,
  description VARCHAR(255)
);

when i check console i get this -

Response { type: "cors", url: "http://localhost:5000/todos", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }

using postman, i am able to interact with my postgres database and execute request properly. i need help because it is not working on client side. how can i solve this?



Solution 1:[1]

could it be that maybe from the server side you are retrieving it as plain text? if so do change it from application/json to text/plain I hope this helps.


(I am editing here since in comment the code won't be visible)


I found a code similar to yours for add I do think the request is wrong here.

app.post('/users', (req, res)=> {
    const user = req.body;
    let insertQuery = `insert into users(id, firstname, lastname, location) 
                       values(${user.id}, '${user.firstname}', '${user.lastname}', '${user.location}')`

    client.query(insertQuery, (err, result)=>{
        if(!err){
            res.send('Insertion was successful')
        }
        else{ console.log(err.message) }
    })
    client.end;
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1