繁体   English   中英

发送到客户端 Express 后无法设置标头

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM