Node.js调用OMDB API获取电影列表时遭遇Can't set headers错误求助
Fixing the "Can't set headers after they are sent" Error in Your Node.js/Express App
Hey there! Let's break down what's causing this frustrating error and how to fix it right away.
What's the Core Issue?
This error pops up because you're trying to send multiple HTTP responses for a single request. HTTP rules strictly state that one request gets exactly one response—once you call res.send() or res.render(), the response is sent to the client, and any later attempts to modify or send another response will trigger this header-related error.
Problems in Your Code
Looking at your /results route, here are the key missteps:
- You start with
res.send("Hello, it workds!");—this sends a response immediately, making all subsequentres.send/res.rendercalls invalid. - The line
res.send(results.search(0).title);uses an undefinedresultsvariable (you meant to use the parseddataobject from the OMDB API response). - You call three different response methods in one route handler, which breaks the one-request-one-response rule.
Corrected Code
Here's the fixed version of your app.js with clear improvements:
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 works! ... and this is the home page"); }); app.get("/results", function(req, res){ // Remove the early res.send—we don't want to send a response before fetching API data request("http://omdbapi.com/?s=california&apikey=thewdb", function(error, response, body){ if (!error && response.statusCode == 200) { var data = JSON.parse(body); // Use console.log for testing instead of res.send (avoids extra responses) console.log(data.Search[0].Title); // Only send one response: render the EJS template with the fetched API data res.render("results", {data: data}); } else { // Handle errors properly so the client doesn't hang waiting for a response res.send("Oops, failed to fetch movie data: " + (error || "Unknown error")); } }); }); app.listen(3000,function(){ console.log("Movie App has started!!!"); });
Quick Extra Tips
- Fix the URL parameter separator: change
&to&in your OMDB API request—this ensures theapikeyparameter is parsed correctly by the API. - Always handle error cases in async callbacks (like failed API requests) to avoid leaving clients stuck waiting for a response.
- Remember: for any single request, you should only call one response method (
res.send,res.render,res.json, etc.).
内容的提问来源于stack exchange,提问作者SDonA
相关产品推荐
相关产品推荐

