HTTP模块
node.js提供了一个创建自己服务器的方式,用起来很简单,首先引用http模块
//引用HTTP模板 var http = require('http');
创建服务实例:http.createServer
//引用HTTP模板 var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type':'text/html'}); res.end('hello World'); }).listen(3000);
req:请求对象
res:响应对象
我想通过启动服务打开页面:在此操作我引用了fs文件系统方法进行传递,代码如下
var http = require('http'); var fs = require('fs'); var server = new http.Server(); server.on('request',function(req,res){ res.writeHead(200,{'Content-Type':'text/html'}); var txt = fs.readFileSync('./index/index.html'); res.write(txt); res.end(); }).listen(1000); console.log('Server running at http://127.0.0.1:1000/');
在此操作我res.write内容是引入index.html 在浏览器打开http://127.0.0.1:1000/就可以展现页面内容了。