搭建一个最简单的node服务器

搭建一个最简单的node服务器

  1、创建一个Http服务并监听8888端口

  2、使用url模块 获取请求的路由和请求参数

var http = require('http');
var url = require('url');

http.createServer(function (req, res) {

    var pathname = url.parse(req.url).pathname; //解析路由请求地址
    var params = url.parse(req.url, true).query; //解析请求参数
    
    console.log(req.method+" Request for " + pathname + " received."); //打印请求

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write(req.method);
    res.write('
pathname:'+pathname);
    res.write('
params:'+JSON.stringify(params));
    res.end();

}).listen(8888);

console.log('Server running at http://127.0.0.1:8888/');

通过浏览器访问  http://127.0.0.1:8888/about?name=zhangsan

浏览器就会打印出请求方式(GET/POST)、访问的路由以及请求参数 

 哇!这可是不需要借助任何软件就可以监听本地端口的服务啊,是不是很简单:)

原文地址:https://www.cnblogs.com/xbblogs/p/8277580.html