HTTP模块
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain'});
response.end('Hello World');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
-
var http = require('http');
创建一个变量来保存引入的http模块,模块引入使用require关键字
-
http.createServer(function (request, response) { response.writeHead(200, { 'Content-Type': 'text/plain'}); response.end('Hello World'); }).listen(8081);
在http中新增一个服务,里面是一个匿名函数,参数request是获取url传过来的信息,response是给浏览器响应信息,
response.writeHead(200, { 'Content-Type': 'text/plain'});
这是设置响应头
response.end('Hello World');
表示给我们页面上面输出一句话并且结束响应,切记一定要结束响应
-
console.log('Server running at http://127.0.0.1:8081/');
在控制输出提示,监听端口是8081
ES6写法
const http = require('http');
http.createServer((request, response)=>{
response.writeHead(200, {
'Content-Type': 'text/plain'});
response.end('Hello World');
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
URL模块
-
url.parse()
url.parse(urlStr, [parseQueryString], [slashesDenoteHost]);
接收参数:
urlStr url字符串
parseQueryString 为true时将使用查询模块分析查询字符串,默认为false
slashesDenoteHost
扫描二维码关注公众号,回复: 12274489 查看本文章默认为false,//foo/bar 形式的字符串将被解释成 { pathname: ‘//foo/bar’ }
如果设置成true,//foo/bar 形式的字符串将被解释成 { host: ‘foo’, pathname: ‘/bar’ }
-
supervisor (监听文件变化,服务自动重启)
npm install -g supervisor
使用方法
supervisor app.js