当给定"application/json"的标头时,JS Fetch 会返回 HTML



我有一个API的获取请求的代码,我知道它返回JSON(请参阅下面的节点-https请求。(然而,即使我为"application/JSON"设置了头,响应也会返回为text/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<在位置0的JSON中。

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

参见:

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

最新更新