我有一个 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。当然,提取给了我典型的错误:意外的令牌< in JSON at position 0.
这是因为当你在客户端使用 header 时,这个 header 是为了告诉服务器“hi server im json”,但默认情况下服务器通常响应为(content-type:text/html),所以你应该指定(content-type : application/json) 也在服务器中。