我正在为我的项目编写一个mocha测试。 测试应该涵盖ajax请求的输出,因此我创建了一个带节点的简单HTTP服务器。
这是当前的代码:
const http = require('http');
const server = http.createServer(function(req, res) {
res.write('test');
});
const port = 5555;
process.on('uncaughtException', function(err) {
console.log("Unhandled Exception, shutting down Server ...")
server.close();
console.log("Server closed!");
console.log(err);
process.exit(1);
});
process.on('SIGTERM', function() {
console.log("Termination called, shutting down Server ...");
server.close();
console.log("Server closed!");
process.exit(1);
});
server.listen('success', function(req, res) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.write(JSON.stringify({
success: true,
message: "Form success!"
}));
res.close();
});
server.listen('fail', function(req, res) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.write(JSON.stringify({
success: false,
message: "Form fail!"
}));
res.close();
});
server.listen(port);
console.log("Server running on Port: " + port);
现在由于某种原因,即使没有使用端口,它总是会抛出EADDRINUSE错误。我杀死了所有node / nodejs进程(没有任何),搜索使用端口(lsof -i tcp:5555)的程序,该程序没有发回任何内容,甚至没有任何重新启动机器差。
这是终端的输出:
Server running on Port: 5555
Unhandled Exception, shutting down Server ...
Server closed!
{ Error: listen EADDRINUSE success
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1249:19)
at listen (net.js:1298:10)
at Server.listen (net.js:1382:7)
at Object.<anonymous> (/home/dominik/Documents/workspace/jelly/test/test-server.js:23:8)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: 'success',
port: -1 }
npm ERR! Test failed. See above for more details.
我当然试图搜索解决方案,但我发现只是使用相同的命令杀死服务器。提前致谢
答案 0 :(得分:1)
您没有正确使用http模块。使用语句server.listen('success',...)
,你对{socket}“成功”starting a UNIX socket server没有任何意义。
以下是http服务器根据请求的网址返回不同响应的示例。我建议您阅读此tutorial。
const http = require('http');
const server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
});
var responseBody = {};
if (req.url === '/success') {
responseBody = {
success: true,
message: "Form success!"
};
}
if (req.url === '/fail') {
responseBody = {
success: false,
message: "Form fail!"
};
}
res.write(JSON.stringify(responseBody));
res.end();
});
const port = 5555;
process.on('uncaughtException', function (err) {
console.log("Unhandled Exception, shutting down Server ...")
server.close();
console.log("Server closed!");
console.log(err);
process.exit(1);
});
process.on('SIGTERM', function () {
console.log("Termination called, shutting down Server ...");
server.close();
console.log("Server closed!");
process.exit(1);
});
server.listen(port, function () {
console.log("Server running on Port: " + port);
});
测试:
curl http://localhost:5555/success
curl http://localhost:5555/fail