【发布时间】: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