因此,我跟随着Sitepoint提供的Full Stack Javascript开发,并且遇到了第6章中发现的问题。我设置了一个基本的http服务器,该服务器应允许传入连接。
当我运行index.js时,会收到一条日志,提示它已在我指定的地址(127.0.0.1:1337)上成功运行
一旦尝试在浏览器中转到该地址,它便无法连接,并且在终端中收到此错误
TypeError: Cannot read property 'toUpperCase' of undefined
at Server.<anonymous> (/Users/user/Documents/Git projects/human-resources/index.js:8:26)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:543:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:105:23)
这条线显然有问题
req.method = req.method.toUpperCase();
但是我不知道为什么,我想也许我将它注释掉就可以了,但是当我这样做时,我遇到了与上面类似的错误,但是这次说res.writeHead不是一个函数
TypeError: res.writeHead is not a function
at Server.<anonymous> (/Users/user/Documents/Git projects/human-resources/index.js:12:9)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:543:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:105:23)
如果有人可以提供我或我的代码哪里出了错的见解,那将在下面列出我的完整代码。
var http = require('http');
http.createServer(function (res,req) {
//A parsed url to work with in case there are parameters
var _url;
//In case the client uses lower case for methods
req.method = req.method.toUpperCase();
console.log(req.method + ' ' + req.url);
if (req.method !== 'GET') {
res.writeHead(501, {
'Content-Type': 'text/plain'
});
return res.end(req.method + ' is not implemented by this server');
}
if (_url = /^\/employees$/i.exec(req.url)) {
//return a list of employees
res.writeHead(200);
return res.end('employee list');
} else if (_url = /^\/employees\/(\d+)$/i.exec(req.url)) {
//find employee by id in the route
res.writeHead(200);
return res.end('a single employee');
} else {
//try to send the static file
res.writeHead(200);
return res.end('static file maybe');
}
}).listen(1337, '127.0.0.1');
console.log('Sever Running at http://127.0.0.1:1337/');
最佳答案
我在http.createServer()中以错误的顺序使用了请求和响应,我使用了响应然后请求,应该是请求然后是响应,就像这样;
http.createServer(function (req,res) {