Express is a web framework for NodeJS like what Slim Framework, Free Free Framework is to PHP. The idea is simple. Minimalist frameworks don’t do much work except for routing requests.
For example, if you want when someone access / on your website, a text saying “Hello World” appears, you do it this way:
var http = require('http'); var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send("Hello World"); }); var server = app.listen(3000, function () {});
If you want to do /hello/{a name here}:
app.get('/hello/:soz', function(req, res) { res.send("Hello " + req.params.soz); });
In the above examples, we have used HTTP GET method. There is a limit in the amount of data we can put in an HTTP header. The POST method is used to send longer data. I will leave the discussion when to use GET, POST and other HTTP verbs in another blog post. Lemme show you how to make a POST request in AJAX using jQuery and retrieve the data in NodeJS.
Client-side/browser-side:
$.ajax({ method: "post", url: "/api/dimoune/", data: { name: "Nayar" }, success: function( data ) { console.log(data); } });
Server-side:
var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: true })); app.post('/api/dimoune/', function(req,res){ // Logic to save to database or something res.send("saved " + req.body.name); });
Notice I had to add body-parser library. Without it, req.body would be not be defined thus you would not be able to access your posted data. Kinda stupid to not include it by default in Express no?
UPDATE:
Another big headache. For posting data with curl command e.g.
curl -H "Content-Type:application/json" -X POST --data '{"name":"nayar","sex":"male"}' http://example.com/api/dimounes
You need to add the following lines in your nodejs file
app.use(bodyParser.json());
Refs:
https://stackoverflow.com/a/18808957/4609496
http://stackoverflow.com/a/25471936
One thought on “WTF Express! Just give me my body. #NodeJS”