【问题标题】:Cannot set headers when they are send to the client发送到客户端时无法设置标头
【发布时间】:2022-02-01 23:46:00
【问题描述】:

当我尝试使用 response.send() 时总是显示一条消息 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.我提供了代码请帮助我修复此错误。

/**
 * Post is used to create new items
 * Put is used to update the items
 * Listen is used to run the server
 * Delete is used to delete an item
 */

const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios').default;
const { response } = require('express');
const app = express();

app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

var city = 'delhi';

app.put('/enter_data',(req,res)=>{
  city = req.body.City;
  if(city === "" || !city){
    res.status(500).send({error: "Write something"});}
    else
    {
      res.send("Now you can see the temperature");
    }
})

app.get('/show_temp',(req,res)=>{
  var sample = "https://api.openweathermap.org/data/2.5/weather?q="+city+'&units=metric&appid=bb16c5275f7a3c1439973f71e4dc811f';
    res.send("Running");
  axios.get(sample)
  .then(response => {
    var t = "Temperature in "+city+" is "+String(response.data.main.temp)+"°C"
    if(t)
    {
    res.status(200).send(t);
    }
  })
  .catch(error => {
    console.log(error);
    //res.status(503).send({status: 1, message: "Messages not available!"});
  })
});

app.listen(5000,()=>{
    console.log("Port Running");
})

【问题讨论】:

  • res.send("Running"); 关闭快速请求,当 axios 尝试(再次)回答请求时,您会收到此错误

标签: javascript node.js express axios


【解决方案1】:

您不能像这样多次发送对请求的响应;一个请求应该等同于一个响应。

app.get('/show_temp',(req,res)=>{
  var sample = "https://api.openweathermap.org/data/2.5/weather?q="+city+'&units=metric&appid=bb16c5275f7a3c1439973f71e4dc811f';
   res.send("Running"); // Here you are sending a response of "Running" to the client
  axios.get(sample)
  .then(response => {
    var t = "Temperature in "+city+" is "+String(response.data.main.temp)+"°C"
    if(t)
    {
    res.status(200).send(t); // Here is where you are sending you're actual response and thus triggering the error.
    }
  })
  .catch(error => {
    console.log(error);
    //res.status(503).send({status: 1, message: "Messages not available!"});
  })
});

对此进行重构,解决方案是:

app.get('/show_temp',(req,res)=>{
  var sample = "https://api.openweathermap.org/data/2.5/weather?q="+city+'&units=metric&appid=bb16c5275f7a3c1439973f71e4dc811f';
  axios.get(sample) 
  .then(response => {
    var t = "Temperature in "+city+" is "+String(response.data.main.temp)+"°C"
    if(t)
    {
    res.status(200).send(t);
    }
  })
  .catch(error => {
    console.log(error);
    res.status(503).send({status: 1, message: "Messages not available!"}); // This is fine so long an error is not thrown AFTER the response
  })
});

我还要注意,对于不同的场景,发送不同响应肯定会有用例。例如,您可能有一个验证步骤,您需要向客户端发送 400 状态。在这种情况下,您希望返回您的响应以防止发送其他响应。

示例 sn-p:

if (badData) {
  return res.sendStatus(400)
}
  res.sendStatus(200)

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 2018-05-25
    • 2021-06-27
    • 2021-06-18
    • 2020-11-14
    • 2020-09-05
    • 2019-02-06
    • 2020-05-20
    相关资源
    最近更新 更多