Serving HTTP requests Learning & Development Telerik School Academy
1. HTTP Fundamentals 2. What is Web Server 3. Create basic server with NodeJS 4. The Request stream object 5. The Response stream object 6. Route requests 7. Using NodeJS as client 2
Communication protocol – Request/Response
HTTP Web server Remote hardware (high performance) Processes clients' requests Delivers web content to clients Usually hosts many web sites Apache and IIS (most common) PHP, ASP.NET, Ruby, Python, NodeJS
Require the 'http' module Create server function (createServer) Request/Response wrapper objects Listen function (specifies port and IP (host)) Headers are objects (keys are lowercased) { 'content-length': '123', 'content-type': 'text/plain', 'content-type': 'text/plain', 'connection': 'keep-alive', 'connection': 'keep-alive', 'accept': '*/*' } 'accept': '*/*' }
Basic server implementation var http = require('http'); http.createServer(function(req, res) { res.writeHead(200, { res.writeHead(200, { 'Content-Type': 'text/plain' 'Content-Type': 'text/plain' }); //return success header }); //return success header res.write('My server is running! ^_^'); //response res.write('My server is running! ^_^'); //response res.end(); //finish processing current request res.end(); //finish processing current request}).listen(1234);
Live Demo
The Request wrapper http.IncommingMessage class Implements the Readable Stream interface Readable StreamReadable Stream Properties httpVersion – '1.1' or '1.0' headers – object for request headers method – 'GET', 'POST', etc url – the URL of the request
Live Demo
The Response wrapper Implements the Writable Stream interface Writable StreamWritable Stream Methods writeHead(statusCode, [headers]) var body = 'hello world'; response.writeHead(200, { 'Content-Length': body.length, // not always valid 'Content-Length': body.length, // not always valid 'Content-Type': 'text/plain', 'Content-Type': 'text/plain', 'Set-Cookie': ['type=ninja', 'language=javascript'] 'Set-Cookie': ['type=ninja', 'language=javascript']});
Methods write(chunk, [encoding]) end() Always call the methods in the following way writeHead write end response.writeHead('Hello world!'); // default encoding: utf8
Live Demo
URL Parsing modules and 'querystring' 'url' and 'querystring' both have parse method var url = require('url'); console.log(url. parse('/status?name=ryan', true)); // logs // { // href: '/status?name=ryan', // search: '?name=ryan', // query: { name: 'ryan' }, // pathname: '/status' // }
Live Demo
http.request and http.get both have (options, callback) signature var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.setEncoding('utf8'); res.on('data', function (chunk) { res.on('data', function (chunk) { console.log('BODY: ' + chunk); console.log('BODY: ' + chunk); }); });}); http.get(" function(res) { console.log("Got response: " + res.statusCode); console.log("Got response: " + res.statusCode);})
- NodeJS official web site - API documentation - NPM documentation - NPM official web site - NodeJS style guide
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране
1. Create file upload web site with NodeJS. You should have the option to upload a file and be given an unique URL for its download. Use GUID and no ExpressJS. 25