[英]Cannot set headers after they are sent to the client Express
我收到錯誤“在將標頭發送到客戶端后無法設置標頭”。請幫助我。當我在 postman 上嘗試相同的操作時,它工作正常。
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/",function(req,res){
const apiKey="ae148f2088da42d7a47ac8e44a4a2768";
const url="https://newsapi.org/v2/top-headlines?country=in&category=business&apiKey="+apiKey;
https.get(url,function(response){
response.on("data",function(data){
const news=JSON.parse(JSON.stringify(data));
res.send("news data"+news);
})
})
})
app.listen(3000, function() {
console.log("Server started on port 3000");
});
每當您從 HTTP stream 獲得一些數據時,就會觸發data
事件。 它將觸發多次,直到所有數據都到達。
因此,使用您當前的代碼,您會為每個請求多次調用send
。
您需要將該數據存儲在某處(例如將其連接到一個變量中),然后僅在end
事件觸發時對其進行處理。
更好的方法可能是停止使用內置的https
模塊並使用更現代的設計(例如 Axios)。
這是問題的答案。問題解決了
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const axios=require("axios");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/",async function(req,res){
const apiKey="ae148f2088da42d7a47ac8e44a4a2768";
const url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=ae148f2088da42d7a47ac8e44a4a2768";
await axios.get(url)
.then((response) => {
const d=response.data.articles[0].source.id;
res.send(d);
}) .catch((error) =>{
console.log(error);
})
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.