Hristijan Ilieski
Hristijan Ilieski

Reputation: 197

JSON data with node.js

I am new to node js programming and I've started developing RESTful API. Now, when I POST the data from terminal with curl like this:

curl -H "Content-Type: application/json" -X POST -d '{"full_name":"Hristijan ilieski", "email":"[email protected]", "password":"123"}' http://localhost:3000/api/login

I am getting the right data in the request body. But when I try to post some json from hurl.it or some other service, the request body is empty. What is the difference and where is the problem? Here's my code:

function registerUser(req, res){
var jsonData = JSON.parse(JSON.stringify(req.body));
//jsonData['key'] should contain the value...
}

Here is an image from the hurl.it request:

hurl request

EDIT

I don't know what I've done, but now when I try to POST a request from hurl.it, I am getting this error:

SyntaxError: Unexpected token f at parse (/home/hristijan/Documents/UrbanAPI/node_modules/body-parser/lib/types/json.js:83:15) at /home/hristijan/Documents/UrbanAPI/node_modules/body-parser/lib/read.js:116:18 at invokeCallback (/home/hristijan/Documents/UrbanAPI/node_modules/body-parser/node_modules/raw-body/index.js:262:16) at done (/home/hristijan/Documents/UrbanAPI/node_modules/body-parser/node_modules/raw-body/index.js:251:7) at IncomingMessage.onEnd (/home/hristijan/Documents/UrbanAPI/node_modules/body-parser/node_modules/raw-body/index.js:308:7) at emitNone (events.js:67:13) at IncomingMessage.emit (events.js:166:7) at endReadableNT (_stream_readable.js:905:12) at nextTickCallbackWith2Args (node.js:441:9) at process._tickCallback (node.js:355:17)

Upvotes: 0

Views: 348

Answers (2)

gibson
gibson

Reputation: 1086

Please try using the the hurl.it body instead of parameters like this:

enter image description here

The whole body is:

{
  "full_name":"Pero Perov",
  "email":"[email protected]",
  "password":"pero123",
  "mobile_number":"076 543 210",
  "home_address":"Perovaca 16b",
  "work_address":"Merovaca 18c"
}

Upvotes: 2

napo
napo

Reputation: 869

Why are you strinfigying then JSON.parsing the request body? That sends you back to square one...

Also, you might need some accept headers and utf-8 encoding, depending on how your backend is set up... (The latter has come back to haunt me before.)

Might want to try Content-type: application/json; charset=utf-8

Upvotes: 0

Related Questions