Node HTTP Module
- Using the module: var http = require('http');
- Creating a server: var server = http.createServer(function(req, res){ . . . });
- Starting the server: server.listen(port, . . . );
Request
Incoming request message information available through the first
parameter “req”
- req.headers, req.body, . . .
Response
Response message is constructed on the second parameter “res”- res.setHeader("Content-Type", "text/html");
- res.statusCode = 200;
- res.writeHead(200, { 'Content-Type': 'text/html' });
- res.write(’Hello World!');
- res.end(' <html><body><h1>Hello World</h1></body></html> ');
Example
var http = require('http');var hostname = 'localhost';
var port = 3000;
var server = http.createServer(function(req, res){
console.log(req.headers);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><body><h1>Hello World</h1></body></html>');
})
server.listen(port, hostname, function(){
console.log(`Listening ${hostname} : ${port}/`);
console.log(`Server running at http://${hostname}:${port}/`);
});
Executing
- Mac: in the console type:
curl http://localhost:3000 - Postman: plugin for chrome
Node path Module
- Using path Module: var path = require('path');
- Some example path methods:
- path.resolve('./public'+fileUrl);
- path.extname(filePath);
Node fs Module
- Use fs module in your application var fs = require(‘fs’);
- Some example fs methods:
- fs.exists(filePath, function(exists) { . . . } );
- fs.createReadStream(filePath).pipe(res);
Comentarios
Publicar un comentario