1

The problem is that I'm getting an error when sending back the data to node js, every time i send something the token seems to increment so something is sent back but i keep getting errors.

im sending a post request from client side javascript to node js with body-parser

this is the client side code

<dl>
    {{#each this}}
    <dd>
        <a href="topic.hbs" onclick="getRoomId({{room_id}})">{{room_name}}</a>

    </dd>
    {{/each}}
</dl>

<script>
    function getRoomId(id){

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'topic.hbs');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(id));
    }
</script>

this is the node js code

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

app.post('/topic.hbs', function(req, res){
  console.warn('body: ',  req.body);
  res.render('topic.hbs')
});

i want the id sent back to node js but keep getting this error.

SyntaxError: Unexpected token 1 in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/Users/Ben255/Desktop/webprojekt/Forum/node_modules/body-parser/lib/types/json.js:158:10)
    at parse (/Users/Ben255/Desktop/webprojekt/Forum/node_modules/body-parser/lib/types/json.js:83:15)
    at /Users/Ben255/Desktop/webprojekt/Forum/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/Ben255/Desktop/webprojekt/Forum/node_modules/raw-body/index.js:224:16)
    at done (/Users/Ben255/Desktop/webprojekt/Forum/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/Ben255/Desktop/webprojekt/Forum/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1145:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
1

1 Answer 1

1

So your problem is you're trying to JSON.Stringify a number, which returns a number. In your console, input JSON.stringify(5) and it will return 5.

You need to send a JSON object, because that's what you're telling the server you're sending when you write xhr.setRequestHeader('Content-Type', 'application/json');. So instead of this:

xhr.send(JSON.stringify(id));

try something like this:

xhr.send(JSON.stringify({id: id}) which will send "{"id":5}".

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

1 Comment

thank you, im new to this web dev stuff still but that solved it :D

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.