You need to enable JavaScript to run this app. Node/Express出现Cannot set headers after they are sent错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Node/Express出现Cannot set headers after they are sent错误求助

错误原因

Error [ERR_HTTP_HEADERS_SENT] 报错的核心是在已经向客户端发送完响应后,又试图执行修改响应头、返回响应内容的操作,你的代码里两个明显逻辑错误直接触发了该问题:

  • 异步执行逻辑和同步代码执行顺序混乱:axios发起的API请求是异步操作,不会阻塞后续代码执行,你在路由末尾直接写了res.end(),会在API请求还没返回结果的时候就直接结束响应,等后续异步回调里执行res.render的时候,响应已经发送完成,自然就会报错。
  • 路由开头不必要的next()调用:如果你的这个POST路由没有后续匹配的中间件逻辑,调用next()也会提前把响应权交出去,可能触发提前发送响应的问题。

其他需要修复的隐性问题

  • 对getLatLongInfoResponse的空值校验不完善,如果接口返回的data是空数组,取[0]会得到undefined,直接调用Object.keys(undefined)会抛出异常。
  • 只有单个请求的场景不需要使用axios.all和axios.spread,属于冗余代码。
  • 所有异步请求的catch块只打印了错误日志,没有给客户端返回响应,会导致请求超时挂起。
  • 你需要把weatherDataResponse传入模板,原来的res.render没传这个参数,模板里无法获取对应数据。

修复后代码

function latLongInfo(results) {
  let obj = {
    method: 'GET',
    url: 'https://forward-reverse-geocoding.p.rapidapi.com/v1/forward',
    params: {
      street: '',
      city: results.city,
      state: results.state,
      postalcode: results.zip,
      country: 'USA',
      'accept-language': 'en',
      polygon_threshold: '0.0'
    },
    headers: {
      'x-rapidapi-key': rapidApiKey,
      'x-rapidapi-host': 'forward-reverse-geocoding.p.rapidapi.com'
    }
  }
  return obj
};

app.get('/', function(req, res) {
  res.render('index', { title: 'idk' });
});

app.post('/getweather', (req, res) => { // 移除不需要的next参数
    const cityWeatherSearch = req.body.cityWeatherSearch
    axios.request(latLongInfo(parseLatLongSearch(cityWeatherSearch)))
    .then(function (response) {
      const getLatLongInfoResponse = response.data[0]
      console.log(getLatLongInfoResponse)
      // 完善空值校验逻辑
      if (!getLatLongInfoResponse || Object.keys(getLatLongInfoResponse).length < 1) {
        return res.render('invalidweather', { title: 'Invalid Results' });
      }
      const lat = getLatLongInfoResponse.lat, lon = getLatLongInfoResponse.lon;
      const latLonString = `${lat},${lon}`;
      // 移除冗余的axios.all,直接发起单个请求
      return axios.get(`https://api.pirateweather.net/forecast/${pirateWeatherKey}/${latLonString}`)
    })
    .then(weatherRes => {
      const weatherDataResponse = weatherRes.data;
      console.log(weatherDataResponse)
      // 把weatherDataResponse传入模板,模板中直接用weather变量访问对应数据
      res.render('weather', { title: 'Weather Results', weather: weatherDataResponse });
    })
    .catch(function (error) {
      console.log(error)
      // 错误场景也要返回响应,避免请求挂起
      res.render('invalidweather', { title: '查询失败,请稍后重试' });
    })  
})

内容的提问来源于stack exchange,提问作者stokedstokely

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 07:39:00