fade Ismaeel
fade Ismaeel

Reputation: 65

Post method from client react to server node

I am using react(frontEnd) with nodejs (backend), I am trying to send post request from client to sever. .

Client Side

Here below I sending the request to server, by using axions. I tried without axions simply calling fetch instead.I tired with adding localhost:5000 and without but I it still not working.

FYI , all the data that I am sending are valid and there are as requested. enter image description here

Server

Here I am trying to handle my request and at least print it to console to verify that my request is as passed valid

enter image description here

result of prints!!!

enter image description here

could you please advise regarding the above ?

After adding body-parser: currently I am getting a undefined object, could you please advise? enter image description here

Upvotes: 0

Views: 2059

Answers (3)

Niroshan Ranapathi
Niroshan Ranapathi

Reputation: 3047

Try This way

const data = {
    name: this.state.additionalCost
};

 axios
      .post(
        '/api/processData',
        data,
        { headers: { 'Content-Type': 'application/json' } }
      )
      .then(function(result) {
       console.log(result);
      });

And use body-parser in express app

import express from 'express';
import bodyParser from 'body-parser';

app.use(bodyParser.json()); 

Upvotes: 1

Harshal Yeole
Harshal Yeole

Reputation: 4983

You don't need to JSON.stringify your data from the react axios request.

Here's an example:

const user = {
    name: this.state.name
};

axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
    .then(res => {
        console.log(res);
        console.log(res.data);
    }
)

For more read Using Axios with React.

Upvotes: 0

Harsh Makadia
Harsh Makadia

Reputation: 3443

Set content type in header and check

axios.post('url', data, {
    headers: {
        'Content-Type': 'application/json',
    }
}

Upvotes: 0

Related Questions