【问题标题】:Cannot set headers after they are sent to the client Express发送到客户端 Express 后无法设置标头
【发布时间】:2020-11-02 11:49:54
【问题描述】:

我收到错误“在将标头发送到客户端后无法设置标头”。请帮助我。当我在邮递员上尝试相同的操作时,它工作正常。

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");
});

【问题讨论】:

    标签: javascript node.js api express


    【解决方案1】:

    每当您从 HTTP 流中获取一些数据时,都会触发 data 事件。它将触发多次,直到所有数据都到达。

    因此,使用您当前的代码,您会为每个请求多次调用 send

    您需要将该数据存储在某处(例如将其连接到一个变量中),然后仅在end 事件触发时对其进行处理。


    更好的方法可能是停止使用内置的https 模块并使用更现代的设计(例如 Axios)。

    【讨论】:

    • 我是新手。我尝试使用 axios 编写这样的代码: axios.get(url) .then((response) => { console.log(response.data); });我收到错误 UnhandledPromiseRejectionwarning。请帮助我
    • 我收到错误 UnhandledPromiseRejectionwarning 错误:请求失败,状态码为 426。请帮助我
    【解决方案2】:

    这就是问题的答案。问题解决了

    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");
    });
    

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2019-12-11
      • 2019-08-27
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多