1

I'm trying to send data from React to Node js. I'm using Ajax. I don't get data by Node.js

This is my code on React :

let id = item.id

 $.ajax({
            url: '/postid',
            type: 'POST',
            data: id

        });
        console.log('React id  : ' + id);

And my code on Node.js

app.post('/postid', function (req, res) {

        console.log("node js ok");
        var getId = req.body.id; // here, i don't get the id value
        console.log("id Node js : " + getId);       
    });

Do you have an idea ? Thank you

6
  • The id is a string i suppose? Commented Jun 15, 2017 at 9:26
  • yes it's a string Commented Jun 15, 2017 at 9:29
  • Try the answer I gave. Commented Jun 15, 2017 at 9:30
  • 1
    Have you used body-parser at node js server? Commented Jun 15, 2017 at 9:34
  • No .. I'm not using body parser Commented Jun 15, 2017 at 9:37

3 Answers 3

1

Do it like this at the frontend:

$.ajax({
  url: '/postid',
  type: 'POST',
  data: JSON.stringify({ id: 'id here' })
});

Use body-parser at the node js server otherwise, you will not be able to get parameters from the request body.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right , i import body-parser, and it works , thank you :) !
1

You should probably use more modern approach like FetchAPI. Use it with Polyfill, because it is not fully supported in all the browsers. With fetch your code will look like this:

fetch('/postid', {
  method: 'POST',
  // headers: {} <-- You can include some headers if you want
  body: JSON.stringify({id: id})

}).then(function(response) {
   return response.json();

}).then(function(json) {
  // json -> is your response from server

}).catch(function(error) {
  // Handle errors here

});

Comments

0

Can you try this

$.ajax({
        url: '/postid',
        type: 'POST',
        data: {"id": id}

    });
    console.log('React id  : ' + id);

3 Comments

it doesn't work .. I have an error on node console : "cannot read property id of undefined "
Do you have bodyparser and cors in you express app
I did'nt have bodyparser, i import it and it works, thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.