Benjamin Kararic
Benjamin Kararic

Reputation: 101

send data from client side javascript to node js

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)

Upvotes: 1

Views: 152

Answers (1)

Tanner
Tanner

Reputation: 2411

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}".

Upvotes: 1

Related Questions