我正在尝试编写一个node.js应用程序来使用omdb api获取电影列表。
当我尝试请求/result
路由时,我收到以下错误:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
at ServerResponse.header (/home/cabox/workspace/APIs/movie_search_app/node_modules/express/lib/response.js:767:10)
at ServerResponse.contentType (/home/cabox/workspace/APIs/movie_search_app/node_modules/express/lib/response.js:595:15)
at ServerResponse.send (/home/cabox/workspace/APIs/movie_search_app/node_modules/express/lib/response.js:145:14)
at Request._callback (/home/cabox/workspace/APIs/movie_search_app/app.js:18:13)
at Request.self.callback (/home/cabox/workspace/APIs/movie_search_app/node_modules/request/request.js:186:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/home/cabox/workspace/APIs/movie_search_app/node_modules/request/request.js:1163:10)
我的app.js文件中的完整代码如下:
var express = require("express");
var app = express();
var request = require("request");
app.set("view engine", "ejs")
app.get("/", function(req, res){
res.send("Hello, it workds! ... and this is the home page");
});
app.get("/results", function(req, res){
res.send("Hello, it workds!");
request("http://omdbapi.com/?s=california&apikey=thewdb", function(error, response, body){
if (!error && response.statusCode ==200) {
var data = JSON.parse(body);
res.send(results.search(0).title);
res.render("results", {data: data});
}
});
});
app.listen(3000,function(){
console.log("Movie App has started!!!");
});
真诚地希望有人可以帮助提供有关如何处理/解决此错误的一些指导。
答案 0 :(得分:2)
您已经发送了一个字符串作为响应,稍后再尝试将呈现的页面发送到客户端,这不起作用...
app.get("/results", function(req, res){
[...]
if (!error && response.statusCode ==200) {
[...]
// HERE IS YOUR PROBLEM
res.send(results.search(0).title);
res.render("results", {data: data});
}
});
What does "res.render" do, and what does the html file look like?
答案 1 :(得分:0)
@moneydhaze感谢您的回复。你让我彻底查看了代码并简单地启动了。似乎res.send和res.render是冲突的。当我拿出res.render并简化代码时;有效。请参阅以下简化代码:
var express = require("express");
var app = express();
var request = require("request");
app.set("view engine", "ejs")
app.get("/", function(req, res){
res.send("This is the Home Page")
});
app.get("/results", function(req, res){
request("http://www.omdbapi.com/?s=guardians+of+the+galaxy&apikey=thewdb", function(error, response, body){
if (!error && response.statusCode ==200){
res.send(body);
}
})
});
app.listen(3000,function(){
console.log("Movie App has started!!!");
});