Search code examples
javascriptjsonnode.jsxmlhttprequestput

Node js, put request with couchdb


I am trying to send a PUT request from JavaScript. I am having trouble sending the value from javascript to node js, it is giving me the edit: error is Unexpected token: o at Object.parse(). on this line var message = JSON.parse(req.responseText); Maybe I should have mentioned I am using bodyParser.

       request.open("PUT", "myurl", true);
       request.setRequestHeader('Content-Type', 'application/json');
       request.send(JSON.stringify({message: "from javascript"}));

from node js I want to send that value to couchDBbut I am not sure how to get the message value passed from javascript

router.put('/fillMessage', function(req, res){
      var request = new XMLHttpRequest();
     //...
    var message = req.body;

    var newData = {_id: data._id, _rev: data._rev, message: "JS value goes here"};
    //...

});

Now I am debugging the node js req variable and there seems to be no json value being passed into it. There is no responseText, or body attributes


Solution

  • Most often Unexpected token: o at Object.parse() means that whatever you're trying to parse is not a JSON-encoded string. It is likely already an object, for example JSON.parse({ two : 2 }) gives that same error.

    JSON.parse tries to turn the input into a string, then parse it as JSON, so in

    var foo = { two : 2 };
    JSON.parse(foo); // throws, equivalent to JSON.parse("[object Object]")
    

    When working with JSON.parse it's a good idea to check that req.responseText is a string first, and wrap JSON.parse in a try/catch block.