nodejs 开启http服务器

1、首先安装node.js

windows地址:https://nodejs.org/dist/v10.15.3/node-v10.15.3-x64.msi

配置成功的标志:

若没成功,也有可能是没有设置环境变量的原因。

2、最简单的服务器

在Eclipse中使用node.js编译代码:

var http = require('http');
http.createServer(function (request, response) {
    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 发送响应数据 "Hello World"
    response.end('Hello World\n');
}).listen(8888);

require函数用来获取node.js提供的模块;

request参数是客户端发来的信息;

response参数是服务器即将发送至客户端的消息;

端口设为8888;

接着浏览器输入127.0.0.1:8888或者localhost:8888即可访问,效果如下:

3、关于url

http://localhost:8888/user?name=赵子隆&city=广州

"http://localhost:8888/"这部分是服务器信息,"user?name=赵子隆&city=广州"这部分是客户端请求参数,合起来才是完整的URL

(这里,user为pathname)

node.js 中 url 模块中的 parse 函数提供了解析参数的功能,使用方法如下:

var http = require('http');
var url = require('url');
var util = require('util');
 
http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
    res.end(util.inspect(url.parse(req.url, true)));
}).listen(8888);

访问结果如下:

也可以单独取出来:

var http = require('http');
var url = require('url');
var util = require('util');
 
http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain'});
 
    // 解析 url 参数
    var params = url.parse(req.url, true).query;
    res.write("用户名::" + params.name);
    res.write("\n");
    res.write("城市:" + params.city);
    res.end();
}).listen(8888);

 效果如下:

(若出现编码问题,浏览器可以右键选择编码为UTF-8)

猜你喜欢

转载自www.cnblogs.com/zhaozilongcjiajia/p/10735071.html