NodeJS 中的 Http
简单的创建一个 HttpServer
http.createServer(function (request, response){
response.writeHead(200, { 'Content-Type': 'text/plain'});
response.write("Hello World");
response.end();
}).listen(8080, '127.0.0.1');
console.log('Server running on port 8080.');
右键运行这个JS代码,可以看到’Server running on port 8080.’的Log信息,表示创建成功。
在browser的URL中输入localhost:8080 来测试,页面上返回Hello World
可以自己创建一个server读取一些数据,比如读取一个文件:
var http = require('http');
var fs = require('fs');
http.createServer(function (request, response){
fs.readFile('data.txt', function readData(err, data) {
response.writeHead(200, { 'Content-Type': 'text/plain'});
response.end(data);
});
// 或者
//fs.createReadStream(`${__dirname}/index.html`).pipe(response);
}).listen(8080, '127.0.0.1');
console.log('Server running on port 8080.');
在browser的URL中输入localhost:8080 来测试,页面上返回data.txt中的信息
可以获取request中的url,可以用来实现rest风格的请求:
//server.js
//var url = require('url');
http.createServer(function(req, res) {
//var pathname = url.parse(req.url).pathname;
//console.log(pathname)
// 主页
if (req.url == "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("Welcome to the homepage!");
}
// About页面
else if (req.url == "/about") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("Welcome to the about page!");
}
// 404错误
else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 error! File not found.");
}
}).listen(8080, "localhost");
console.log('Server running on port 8080.');
在browser的URL中输入http://localhost:8080/about 来测试,页面上返回Welcome to the about page!
除开了在Browser中的url中直接来验证外,还可以自己手动在 js 中发送请求来测试上面写的 server 是否已经正常运行:
//client.js
var http = require('http');
return http.get({ //发送一个 get 请求,但是没有post请求的简写
//host: 'localhost',
//hostname: "",
port: 8080,
path: '/about'
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log(body); //Welcome to the about page!
//var parsed = JSON.parse(body);
// callback({
// email: parsed.email,
// password: parsed.pass
// });
});
});
request方法用于发出HTTP请求,它的使用格式如下。http.request(options[, callback])
request方法的options参数,可以是一个对象,也可以是一个字符串。如果是字符串,就表示这是一个URL,Node内部就会自动调用url.parse(),处理这个参数。
- options对象可以设置如下属性。
- host:HTTP请求所发往的域名或者IP地址,默认是localhost。
- hostname:该属性会被url.parse()解析,优先级高于host。
- port:远程服务器的端口,默认是80。
- localAddress:本地网络接口。
- socketPath:Unix网络套接字,格式为host:port或者socketPath。
- method:指定HTTP请求的方法,格式为字符串,默认为GET。
- path:指定HTTP请求的路径,默认为根路径(/)。可以在这个属性里面,指定查询字符串,比如/index.html?page=12。如果这个属性里面包含非法字符(比如空格),就会抛出一个错误。
- headers:一个对象,包含了HTTP请求的头信息。
- auth:一个代表HTTP基本认证的字符串user:password。
- agent:控制缓存行为,如果HTTP请求使用了agent,则HTTP请求默认为Connection: keep-alive,它的可能值如下:
- undefined(默认):对当前host和port,使用全局Agent。
- Agent:一个对象,会传入agent属性。
- false:不缓存连接,默认HTTP请求为Connection: close。
- keepAlive:一个布尔值,表示是否保留socket供未来其他请求使用,默认等于false。
keepAliveMsecs:一个整数,当使用KeepAlive的时候,设置多久发送一个TCP KeepAlive包,使得连接不要被关闭。默认等于1000,只有keepAlive设为true的时候,该设置才有意义。
// server.js
//当客户端采用POST方法发送数据时,服务器端可以对data和end两个事件,设立监听函数。
var http = require(‘http’);
http.createServer(function (req, res) {var content = "";
req.on('data', function (chunk) {
content += chunk;
});
req.on('end', function () {
res.writeHead(200, { "Content-Type": "text/plain"});
res.write("You've sent: " + content);
res.end();
});
}).listen(8080, ‘localhost’);
console.log(‘Server running on port 8080.’);// client.js
var http = require(‘http’);
var querystring = require('querystring');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var req = http.request({ //没有Post方法,只能发送原生的request请求
//host: 'http://localhost',
//hostname: "",
port: 8080,
path: '/',
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log(body);//You've sent: msg=Hello%20World!
//var parsed = JSON.parse(body);
// callback({
// email: parsed.email,
// password: parsed.pass
// });
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
还没有评论,来说两句吧...