Project Development

Tuesday, June 10, 2014

cURL HTTP GET & POST with a Node.js built Server

Recently, I have my server built with Node.js and MongoDB as the database.

Here comes the structure. The server is running in Node.js. MongoDB provides the database support. So the http requests will be accepted and handled by the node.js code. Based on the request, the server will insert, delete, query, or update the data in the database. People call this RESTFUL API. Even I don't know if there is another way to achieve this, it's just so native to me.

Once the basic server handling(API) code is done, it needs to be tested.

The most native way to test it is using a browser. Yes, that's what I use for testing if the server is running actively. I also use this to test my HTTP GET request.

Then, what should I do if I need to test with POST method?

Here comes cURL.

The format is like: 

curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' URL

-d specify the actual Data of Posting Method.

-H specify the Content Type.

-X specify the Custom Request Method.

So, to send GET request, it would be like:

curl -X GET URL

BTW, using body-parser installed from npm, the parser could not parse the number with leading zeros. Also, every mongdb operation in nodejs must have a callback function.

Friday, May 30, 2014

How to Client IP Address in NodeJS

One single function could just solve your problem.
function getClientAddress(request) {
 with (request)
  return (headers['x-forwarded-for'] || '').split(',')[0]
    || connection.remoteAddress
}