您的位置:首页 > 理论基础 > 计算机网络

nodejs http simple demo

2017-07-11 23:06 375 查看
var http = require('http');

http.createServer(function(req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write('<h1>Node.js</h1>');

res.end('<p>Hello World</p>');

}).listen(3000);
console.log("HTTP server is listening at port 3000.");

详解:

这段代码中,http.createServer 创建了一个 http.Server 的实例,将一个函数

作为 HTTP 请求处理函数。这个函数接受两个参数,分别是请求对象( req )和响应对象

( res )。在函数体内,res 显式地写回了响应代码 200 (表示请求成功),指定响应头为

'Content-Type': 'text/html',然后写入响应体 '<h1>Node.js</h1>',通过 res.end

结束并发送。最后该实例还调用了 listen 函数,启动服务器并监听 3000 端口。



var http = require('http');

var server = new http.Server();

server.on('request', function(req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write('<h1>Node.js</h1>');

res.end('<p>Hello World</p>');

});

server.listen(3000);

console.log("HTTP server is listening at port 3000.");

get post

var http = require('http');

var url = require('url');

var util = require('util');

http.createServer(function(req, res) {

res.writeHead(200, {'Content-Type': 'text/plain'});

res.end(util.inspect(url.parse(req.url, true)));

}).listen(3000);

在浏览器中访问 http://127.0.0.1:3000/user?name=byvoid&email=byvoid@byvoid.com,我
们可以看到浏览器返回的结果:

{ search: '?name=byvoid&email=byvoid@byvoid.com',

query: { name: 'byvoid', email: 'byvoid@byvoid.com' },

pathname: '/user',

path: '/user?name=byvoid&email=byvoid@byvoid.com',

href: '/user?name=byvoid&email=byvoid@byvoid.com' }

通过 url.parse①,原始的 path 被解析为一个对象,其中 query 就是我们所谓的 GET

请求的内容,而路径则是 pathname。

获取post请求体内容,不要在生产中使用这种方式

var http = require('http');

var querystring = require('querystring');

var util = require('util');

http.createServer(function(req, res) {

var post = '';

req.on('data', function(chunk) {

post += chunk;

});

req.on('end', function() {

post = querystring.parse(post);

res.end(util.inspect(post));

});

}).listen(3000);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: