0

Send data React to Node

If send data with axios.

is it correct?

react:

let data = {pp: number};
    axios.post('http://localhost:3001/number', {
        body:  data
    }). then((response) => {
        console.log('data submitted success');
    }).catch((error) => {
        console.log('got err', error);
    });

this in server

router.post('/', function (req, res) {
  var countValue = req.body;
  console.log('CountValue is', countValue);
});
alivadjid
  • 1
  • 4
  • 1
    It looks like you're posting to a route called `/number`, and supporting a route called `/`, the root path. Is the router nested under `number` already? Those two have to be the same for your backend to receive the POST. – Jake Worth Apr 22 '20 at 13:04
  • Does this answer your question? [axios post request to send form data](https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data) – Nazkter Apr 22 '20 at 17:16
  • What do you mean by "correct"? Is there any problem with the given code? – Nico Haase Apr 23 '20 at 11:24
  • I tried to send data with fetch. With this code it works too. And how to take response from server? – alivadjid Apr 24 '20 at 14:56
  • well i rave a responce. Added this in server res.end(JSON.stringify(countValue)); in front it return this: [object Object]{config: Object {...}, data: 34, headers: Object {...}, request.... I need to "data: 34" assign in variable. Does it mean that I should use (bodyParser.json()? – alivadjid Apr 24 '20 at 15:32

1 Answers1

0

It seems you need to put bodyParser.json() in your middleware. For example:

app.use(bodyParser.json());

After that, you could use below code as your HTTP response in the controller.

res.status(200).json({ results: countValue });

I believe you don't need to use JSON.stringify(countValue)

Feel free to share more details for us :)

Will
  • 325
  • 2
  • 9