我在 Node 中编写了一个相当复杂且有效的 js 脚本。我升级了我的服务器,发现它失败了。回到基础知识,我发现当我转到 http://www.mapworldlive.com:8899/test 时,这个简单的脚本失败并显示控制台消息,如下所示。从我的浏览器:
var http = require("http");
var express = require('express')
var app = express()
var server = http.createServer(app);
server.on('request', app);
server.listen(8899);
var chttime=new Date(),showdate=chttime.toDateString(),secs=chttime.getSeconds(),mins=chttime.getMinutes(),hrs=chttime.getHours(),day=chttime.getDay(),month=chttime.getMonth(),year=chttime.getFullYear();
console.log("Test Server started: "+hrs+":"+mins+" "+showdate);
app.use('/test',function(req, res) {
console.log("hello world")
res.end()
})
回应:
Test Server started: 14:23 Sat Feb 04 2017
hello world
Error: Can't set headers after they are sent.
请帮助我,以便其他人在我的情况下也能得到帮助!
堆栈跟踪:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at expressInit (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/express/lib/
iddleware/init.js:23:42)
at Layer.handle [as handle_request] (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node
modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/express/lib/
outer/index.js:312:13)
at /var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/express/lib/router/index.
s:280:7
at Function.process_params (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/
xpress/lib/router/index.js:330:12)
at next (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/express/lib/router/
ndex.js:271:10)
at query (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/express/lib/middle
are/query.js:44:5)
at Layer.handle [as handle_request] (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node
modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/vhosts/mapworldlive.com/dev.mapworldlive.com/node_modules/express/lib/
outer/index.js:312:13)
最佳答案
这两行基本相同:
var server = http.createServer(app);
server.on('request', app);
所以我的猜测是您运行了两次请求处理,第二次发现第一个已经调用了 response.end
。
删除 server.on
并重试。还有一个个人提示:不要调用 res.end
,而是向浏览器输出一些内容,以便您可以轻松测试,例如 res.send('Hi!')
。
关于javascript - 使用带有非常简单脚本的 Node 发送后无法设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42041659/