第二课 创建http server

nodejs 不需要单独安装服务器软件 tomcat 、apache、 iis

看下面的代码创建了http服务器,并输出一些简单的响应内容

//引入http 模块

var http = require('http');

//创建服务器并监听端口5000

//createServer(function(req,res){}) 回调函数 req、res 就是我们常见的request 和response对象

http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.write('中国222');
res.end('end');

}).listen(5000);

将此代码保存文件为http.js  注意选择编码utf-8否则出现 中文乱码问题

然后在命令行 进入程序所在目录D:/nodejs

执行: node http.js

这时候控制台没有任何输出

我们启动浏览器 地址输入:http://localhost:5000

发现浏览器正确输出了我们的结果:

 
分类: nodejs基础
原文地址:https://www.cnblogs.com/3dianpomian/p/4847264.html