首页 > 解决方案 > 当给定“应用程序/json”的标头时,JS Fetch 返回 HTML

问题描述

我有一个我知道返回 JSON 的 API 获取请求的代码(请参阅下面的节点 - https 请求。)但是,即使我为“应用程序/json”设置了标题,响应也会以文本/html 的形式返回。这没有任何意义,因为所有手册都显示我的代码是正确的。没有太多深入研究为什么我要返回 html。

JS 获取

const submit = () => {
        const API_KEY = '4cb192e459db0f503de68ecd35c8fde4'
        // const CITY = 'paris'

    fetch(`api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API_KEY}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(async response => {
        // response.json();

        console.log(response.text())
    })
    .then(data => console.log(data))
    .catch(err => {
        console.log(err);
    })
}

节点 HTTPS

const https = require('https')

const API_KEY = '4cb192e459db0f503de68ecd35c8fde4'

const options = {
    hostname: 'api.openweathermap.org',
    port: 443,
    path: `/data/2.5/weather?lat=35&lon=139&appid=${API_KEY}`,
    method: 'GET'
}

const req = https.request(options, res => {
    console.log(`statusCode: ${res.statusCode}`)

    res.on('data', d => {
        process.stdout.write(d)
    })
})

req.on('error', error => {
    console.error(error)
})

req.end()

我什至尝试将响应正文作为可读流读取,并且仍在尝试理解这一点,因为响应确实返回了正文。

为了清楚起见,我得到了 200 响应,基本响应类型,对于获取,响应是 text/html。当然,fetch 给了我一个典型的错误: Unexpected token < in JSON at position 0。

标签: jsonfetchfetch-api

解决方案


使用 Create-React-App 时,它通过 localhost 路由 api 请求。将 Https:// 添加到 api 请求的前面解决了这个问题。

看:

使用 create-react-app 获取 api 数据


推荐阅读