Node.js 学习笔记02-Http的响应操作
第3章和第4章主要介绍了Node.js的一些基本思想,例如Node.js是异步执行的,基本以执行,回调为主等等。
01这篇笔记里介绍了如何使用Node.js构建一个服务器,让我们请求之后可以返回”Hello World“。接下来要介绍一下,如何用Node.js来完成一些Http的基本操作。
1.设置请求头
我们在HelloWorld里写了关于设置响应头的代码了。
var http = require('http');
http.createServer(function (req, res) {
// 我们在这一行设置了Http响应头的相关信息
res.writeHead(200, {'Content - Type':'text/plain'});
res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log("Server running at http://127.0.0.1:3000/n");
当然我们也可以设置多个响应头,就像这样。
res.writeHead(200, {
'Content - Type':'text/plain',
'Connection':'keep-alive'
});
2.重定向
我们可以用301的http状态码让服务器重重定向,跳转到另外一个网址上去。
就像这样。
var http = require('http');
http.createServer(function (req, res){
res.writeHead(301,{'Location':'http://www.baidu.com'});
res.end('Hello world');
}).listen(3000, "127.0.0.1");
3.用Node.js完成路由功能。
上面的代码都只能响应单一的请求,能不能让Node.js响应多个请求呢?当然可以。
Node.js的URL模组可以让我们很方便的解析请求来的URL。
只要这样
var pathname = url.parse(req.url).pathname;
,我们就能取到请求的路径了。我们可以根据用户请求的路径不同,让服务器做出不同的动作。
var http = require('http');
url = require('url');
http.createServer(function (req, res){
// 获取到请求的路径
var pathname = url.parse(req.url).pathname;
// 用户请求根路径,显示Home Page
if (pathname==='/') {
res.writeHead(200,{
'Content_type':'text/plain'
});
res.end('Home Page\n');
console.log('Home Page');
}else if (pathname==='/about') {// 用户请求/about,显示About US
res.writeHead(200,{
'Content_type':'text/plain'
});
res.end('About US');
console.log('about');
}else if (pathname==='/redirect') {// 用户请求/redirect,跳转到根路径
res.writeHead(301,{
'Location':'/'
});
res.end();
console.log('null');
}else{// 除此之外,显示Page not found
res.writeHead(404,{
'Content_type':'text/plain'
});
res.end('Page not found\n');
};
}).listen(3000, "127.0.0.1");