2016.09.09 如何创建nodejs HTTP服务器
2016-09-10 本文已影响48人
Success85
基本流程
- 首先:引入node的核心模块http:require("http");
- 通过http的createServer创建.http.server的一个实例,在里面可以输入你要输出的一些信息,
- 使用http.server的实例的listen的方法。监听ip和端口,并传入一个回调函数
示例
const http = require('http');//调用http模块
const ip = "192.168.238.128";//定义服务器的IP
const port = 3000;//定义端口
var a = function(req,res){
res.writeHead(200,{'content-type':'text/html'});
console.log(res);
res.write('dajiabuyaofuzao');
res.end('bu yao fu zao');
}
var server = http.createServer(a);
var c = function(){
console.log('server is running');
}
server.listen(port,ip,c);
nodejs HTTP服务器请求返回参数
- statusMessage 状态信息
- 普通
Request URL:请求的网址
Request Method:请求方式
Status Code: 返回状态码
Remote Address:请求地址及端口 - 请求头信息
host: '192.168.235.128:6666',
connection: 'keep-alive',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
accept: '/',
referer: 'http://192.168.235.128:6666/',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'zh-CN,zh;q=0.8,en;q=0.6' - 响应头信息
Connection:close 链接状态
Content-Type:text/html 返回类型
Date:Sun, 11 Sep 2016 12:43:59 GMT 返回时间
Server:Apache/2.2.3 (Red Hat) 服务器信息
Transfer-Encoding:chunked
X-Powered-By:PHP/4.4.9 版权信息
Cache-control:private
Content-Encoding:gzip
Content-Type:text/html; charset=utf-8
Date:Sun, 11 Sep 2016 12:50:17 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=99
Pragma:no-cache
Server:Apache/2.4.18 (Win32) OpenSSL/1.0.2e mod_fcgid/2.3.9
Set-Cookie:PHPSESSID=okc2bq1i1rpi0bhq0njoqgc591; path=/
Set-Cookie:ZDEDebuggerPresent=php,phtml,php3; path=/
Transfer-Encoding:chunked
Vary:Accept-Encoding
作业(nodejs)
1、打印一个空心的菱形
2、打印一个空心的梯形
3、打印一个回形
4、字符串每3个加逗号分隔
5、创建一个http服务,把用户请求整理出来