json - 当给定“应用程序/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。
解决方案
使用 Create-React-App 时,它通过 localhost 路由 api 请求。将 Https:// 添加到 api 请求的前面解决了这个问题。
看:
推荐阅读
- docker - Docker 运行命令在主机上找不到目录
- mysql - 根据真/假标志对日期进行不同的排序
- python - 如何使用 python Ray 在一个大列表上并行化?
- vue.js - Vue路由器在按键上重复路由
- php - 在会话 Laravel 7 中更改变量
- ios - AVPlayer 可以从 API 端点正确流式传输视频文件吗?
- python - 如何使用kafka-python计算主题中的记录(消息)数
- c++ - 使用 FFmpeg API 将 RTP 有效负载数据写入音频文件
- grafana - 如何使用 Grafana 设置 Prometheus Operator 以启用基本 Kubernetes 监控
- javascript - 为 Google 图表格式化数组/对象数据