Skip to content

POST http://localhost:3000/data 400 (Bad Request) when trying to send data from client to server

Hey guys so i’ve got some problem with sending data from client-side to server-side. Basically i have a function that on click is setting variable called categorySearch to a string e.g categorySearch = “pork” and send it to server; But for some reason i keep getting error mentioned in the title. Here’s some code: Client Side

function getRecipes(category){
    const categorySearch = category.alt;
    const options = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json'
        },
        body: categorySearch
    }
    const response = fetch('/data', options);
    console.log(response);
}

Server-side

const express = require('express');
const app = express();
const fetch = require('node-fetch');
require('dotenv').config();
const API_KEY = process.env.API_KEY;
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({ limit: "1mb"}));

app.post('/data', (request, repsonse) => {
    console.log(request.body);
})

Not sure what i did wrong, i haven’t worked much with backend so don’t have much knowledge either, any help very appreciated 🙂

My end-goal for that is to be able to send the data that users enters or in this case clicks on to the server, then in the server-side make an api call to the search engine, take the data i need, send it back to client-server and display it on the page.

Answer

Reason:-

The 400 Bad Request Error is an HTTP response status code that indicates that the server was unable to process the request sent by the client due to invalid syntax

as per your code your sending data from client as json and retrieving that in your server as plain text, so instead of sending it as application/json use text/plain or remove that header part so it will work fine, check out the below-attached code.

Client-side:-

function getRecipes(category){
const categorySearch = category.alt;
const options = {
    method: 'POST',
    headers: {
        'Content-type': 'text/plain', // or remove this headers section
    },
    bodydata: categorySearch
}
 const response = fetch('/data', options);
 console.log(response);
}

Server side:

app.post('/data', (request, repsonse) => {
 console.log(request.body.bodydata);
})

hope this will give you some idea about the error. read here more about 400 error