0

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

5
  • is isTransportationCost only coming as undefined? I feel all of your parameters should arrive as undefined. Also +1 for clean code Commented Jun 29, 2018 at 7:10
  • req.body also undefined in here ? Commented Jun 29, 2018 at 7:14
  • The whole request, as well as all parameters Commented Jun 29, 2018 at 7:14
  • 3
    Images of code or exception are not helpful, it would be better to use textual representation instead. Commented Jun 29, 2018 at 7:33
  • Agreed, post code/text so it's searchable for people having the same issue. Commented Jun 29, 2018 at 7:45

3 Answers 3

1

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()); 
Sign up to request clarification or add additional context in comments.

3 Comments

I tried , i.prntscr.com/5vJ6ijrORx_s5EMydajgdg.png this what I am getting on server side
did you add bodyParser also ?
yes, to access my data I should type the following ,req.body.body.addtionalCost
0

Set content type in header and check

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.