我是nodeJS技术的新手,实际上我想创建一个服务器并提供基于 request.url 的另外两个文件的路由但是我运行,它显示了上面的错误,它在哪里显示无效的状态代码,
这是我的代码
app.js
var url = require('url')
var fs = require('fs')
function renderHTML(path , response){
fs.readFile(path,null, function(error , data){
if(error){
response.write('file not found')
} else{
response.writeHead(data)
}
response.end()
})
}
module.exports = {
handleRequest : function(request , response){
response.writeHead(200, {'Content-Type' : 'text/html'})
var path = url.parse(request.url).pathname;
switch(path) {
case '/' :
renderHTML('./index.html', response)
break;
case '.login' :
renderHTML('./login.html', response)
break;
default :
response.write('route not defined')
response.end()
}
}
}
我的server.js看起来像
let http = require('http')
var app = require('./app.js')
http.createServer(app.handleRequest).listen(8001)
我的根目录中有index.html和login.html ..
上面的代码有什么问题。 请帮帮我。
答案 0 :(得分:2)
要呈现您的html文件,您希望使用response.write()
,而不是response.writeHead()
。
response.writeHead()
用于编写http响应的标头,如response.writeHead('404')
,如果找不到该文件。这就是您收到错误消息“无效状态代码”的原因,因为该函数需要有效的http代码状态(数字)。
使用response.write()
,您可以发送文件内容,并在内部调用response.writeHead()
来设置状态(200)。
例:
function renderHTML(path, response) {
fs.readFile(path, null, function(error, data) {
if (error) {
response.writeHead('404')
response.end('file not found')
} else {
response.write(data)
}
})
}