问题描述
我正在使用POST方法在根路由/
上提交表单数据。服务器使用表单数据从其他API中获取一些数据。但是,在响应中,我总是收到text/html
数据,而不是json
响应。
表单处理程序
function handleSubmit(event) {
event.preventDefault()
showSpinner()
const tripName = document.getElementById('tripName')
const tripDest = document.getElementById('tripDestination')
const startDate = document.getElementById('fromDate')
const endDate = document.getElementById('toDate')
tripDetails.tripName = tripName.value
tripDetails.tripDest = tripDest.value
tripDetails.startDate = startDate.value
tripDetails.endDate = endDate.value
fetch('/',{
method : 'POST',headers : {
"Content-Type" : "application/json"
},body : JSON.stringify({tripDetails : tripDetails})
}).then((res) => {
console.log(res.headers.get('Content-Type'));
res.text().then((data) => {
return data;
});
})
}
对客户端的响应
但是,当我打开 Postman 来测试服务器端时,会从API中获得所需的json响应。
服务器端代码
app.post('/',(req,res) => {
console.log(req.body);
fetch(`http://api.geonames.org/searchJSON?name=${req.body.tripDest}&username=${GEONAMES_API}`)
.then(data => data.json())
.then(data => {
destCoords.latitude = data.geonames[0].lat
destCoords.longitude = data.geonames[0].lng
return fetch(`https://api.darksky.net/forecast/${DARK_SKY_API}/${destCoords.latitude},${destCoords.longitude}`)
})
.then(data => data.json())
.catch(err => `Error >>> ${err}`)
.then(data => {console.log(data);res.send(data)})
.catch(err => `Error in sending data to client >>> ${err}`)
})
服务器端输出
这里到底发生了什么?我无法理解客户端如何无法接收服务器json数据。
此外,我正在使用webpack构建我的应用程序。自从我第一次使用它以来,不确定是否会导致任何问题。 dist
文件夹创建正确,应用也成功编译。
解决方法
使用:
.then(data => data.json())
在表单处理程序上。