本地创建一个node服务
安装node.js
在项目目录下新建server.js
var http = require('http')
var fs = require('fs')
var url = require('url')
http.createServer(function(request, res) {
var pathname = url.parse(request.url).pathname
console.log('Request for ' + pathname + ' received.')
var firstDir = pathname && pathname.split('/')[2]
var ContentType = null
if (firstDir && firstDir === 'static') {
ContentType = {'Content-Type': 'text/css'}
} else {
ContentType = {'Content-Type': 'text/html'}
}
fs.readFile(pathname.substr(1), function(err, data) {
if (err) {
res.writeHeader(404, {
'content-type': 'text/html;charset="utf-8"'
})
res.write('<h1>404错误</h1><p>你要找的页面不存在</p>')
res.end()
} else {
res.writeHeader(200, {
'content-type': 'text/html;charset="utf-8"'
})
res.write(data.toString())
res.end()
}
})
}).listen(8081)
console.log('服务器开启成功')
打开命令窗口,cd到项目目录下,运行node server.js,控制台会输出“服务器开启成功”
在浏览器中输入“localhost:8081/”+你要访问的文件名称;例如localhost:8081/index.html
参考