//请求地址不同返回不同的响应
var http = require("http");
// 1.创建 server
var server = http.createServer();
// 2.监听 request 事件
server.on('request',function(req,resp){
console.log("获取客户端请求");
// console.log("获取客户端ip地址:",req.socket.remoteAddress);
// console.log("获取客户端请求端口号:",req.socket.remotePort);
// 请求地址不同返回不同的响应
// req.url 是 端口号之后的
// 中文乱码 解决
// 在服务端默认发送的数据,其实是 utf8 编码的内容
// 浏览器不知道 是 utf8 编码
// 浏览器在不知道服务器响应内容的编码的情况下 会按照当前操作系统的默认编码去解析
// 中文操作系统默认是 gbk
// 在http协议中,Content-type 是用来告知对方我发给你的数据内容是什么类型
// http://tool.oschina.net/commons 查询表
// resp.setHeader("Content-type","application/json"); //或
// resp.setHeader("Content-type","text/plain;charset=utf-8"); //普通文本
// 除了 Content-type 可以用来指定编码 也可以在html页面中通过meat(元数据:用来描述网页的一下信息)来声明当前文本的编码格式,浏览器也会识别他
var url = req.url;
switch(url){
case "/"://http://127.0.0.1:3000
resp.end("3000");
break;
case "/html"://http://127.0.0.1:3000/html
resp.setHeader("Content-type","text/html;charset=utf-8"); //html 文本
resp.end("<h1>html type <a href=''>a链接</a></h1>");
break;
case "/index": // http://127.0.0.1:3000/index
resp.end("index page");
break;
case "/login":// http://127.0.0.1:3000/login
resp.end("login page");
break;
case "/logout":// http://127.0.0.1:3000/logout
resp.end("logout page");
break;
case "/products":// http://127.0.0.1:3000/products
resp.setHeader("Content-type","text/plain;charset=utf-8"); //普通文本
var products = [{
name:"商品一",
price:"199"
},{
name:"商品二",
price:"299"
},{
name:"商品三",
price:"399"
},{
name:"商品shi 456454 ghg",
price:"499"
}]
resp.end(JSON.stringify(products));//中文乱码 19 解决
break;
default:
resp.end("404 Not Found.")
break;
}
})
// 3.绑定端口号
server.listen(3000,function(){
console.log("服务器启动成功,可以通过 http://127.0.0.1:3000 进行访问");
//通过ip访问 192.168.0.248:3000/products
})
运行
在对应的目录下 输入 cmd 打开cmd窗口
node 文件名.js
然后再浏览器 输入地址测试