3

I'm building my first project so I'm pretty new to Js, Node Js, etc. My question is how do you send data from Javascript file to the backend in this case Node.js file, the Javascript file is link to the html file.

MY HTML:

<button type="button" class="btn btn-light bn" id="1"><span 
class="dif">3/8"</span> Q2.15</button>

MY JAVASCRIPT:

const button = document.getElementById('1');

button.addEventListener('click', function(e) {


fetch('/clicked', {
    method: 'POST', 
    body: JSON.stringify({ id: e.currentTarget.id }),
 })
   .then(function(response) {
       if(response.ok) {
       console.log('Click was recorded');
        return;
      }
     throw new Error('Request failed.');
  })
    .catch(function(error) {
    console.log(error);
    });
}); 

NODE JS CODE:

app.post('/clicked', (req, res) => {
  const click = JSON.parse(req.body).id;
  Product.findOne({id: click}, function(err, foundLList) {
        if(err) {
            console.log(err);
        } else {
            console.log(foundLList);
        }
    } 
  ); 
});

What I´m trying to accomplish is to send the id of the button clicked to the backend(node.js) but is not working i tried to console.log thr req and req.menu and when I do req.menu appears only {} and when I add .id to the request is shows undefined.

1 Answer 1

2

In your fetch() call, you should specify the Content-Type header as application/json. This way, your server knows how to handle it.

fetch('/clicked', {
  method: 'POST',
  body: JSON.stringify({ id: e.currentTarget.id }),
  headers: {
    'Content-Type': 'application/json'
  }
})

On the Node.js side, it looks like you're using Express. Make sure you're also using the Body Parser middleware, which can handle your JSON.

const bodyParser = require('body-parser');
app.use(bodyParser.json());

Alternatively, for newer/current versions of Express, you can use express.json().

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

4 Comments

I tried to using the headers and everything but is giving me the error SyntaxError: Unexpected token u in JSON at position 0
And I know that is when the value is undefined and have bodyParser set up and all
@LuisGonzalez undefined isn't valid in JSON. You have to use null instead.
thank you Brad for your help I resolve i was stringify a data that wasn´t JSON

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.