【发布时间】:2020-08-10 20:28:56
【问题描述】:
我正在使用 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 文件夹创建正确,应用也编译成功。
【问题讨论】: