Maramal
Maramal

Reputation: 3474

How to send form data to the server with JavaScript

I am working with two servers, one for React (on address http://localhost:3000/contact) and another for Express (on address http://localhost:5000/). I want to send form data object through some HTTP request approach as a POST method but I get empty object on the "backend" side.

I have a simple form with an onSubmit event which firstly creates an object with the form data values:

const data = {
    firstInput: evt.target.elements.firstInput.value,
    secondInput: evt.target.elements.secondInput.value
}

Note: I tested If get all the data until here with DevTools and React Dev tools, until here it works great.

And the second server with Express that just have a simple endpoint which should receive this data or at least print what I sent in the req.body object:

server.post("/", (req, res) => {
    res.end(req.body);
});

Note 2: Also tested this endpoint and it works fine but req.body gets an empty object.

I have tested several methods like:

Native fetch API:

fetch("http://localhost:5000/", {
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
    }).then(res => {
        console.log(res);
    });

Error:

Error

Also, tried with async / await approach on fetch API but I wasn't sure about using it on React component.

I also have tried http API but I got with the same.

I guess my first question is how to send properly formatted the data from the component side to the server side. Thanks anyway.

Upvotes: 0

Views: 691

Answers (1)

Manzurul Hoque Rumi
Manzurul Hoque Rumi

Reputation: 3104

Use this package query-string You can use like this:

import queryString from 'query-string';
fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important
    body: queryString.stringify({for:'bar', blah:1}
});

Upvotes: 1

Related Questions