服务器不断向客户端发送“ text / html”数据

问题描述

我正在使用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;
        });
    })
}

对客户端的响应

ClientData

但是,当我打开 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}`)

})

服务器端输出

ServerResponse

这里到底发生了什么?我无法理解客户端如何无法接收服务器json数据。

此外,我正在使用webpack构建我的应用程序。自从我第一次使用它以来,不确定是否会导致任何问题。 dist文件夹创建正确,应用也成功编译。

解决方法

使用:

.then(data => data.json())

在表单处理程序上。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...