reactjs - 如何从 react 应用程序中获取 swapi?
问题描述
我正在尝试使用以下代码从反应应用程序调用Star Wars Api (swapi) :
export function getAsync(route: string, baseUrl: string) {
// var url = baseUrl + "/" + route;
let url = "http://swapi.dev/api/planets?page=1";
let status: number;
return fetch(url, {
headers: {
"content-type": "application/json",
},
})
.then((response: any) => {
status = response.status;
console.log(response);
return response.json();
})
//more stuff
}
但是我收到此错误:
Access to fetch at 'http://swapi.dev/api/planets?page=1' from origin 'http://localhost:3000' has been
blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not
allowed for a preflight request.
我需要做什么来修改我的获取请求?我注意到连接到此 API 的示例使用了 swapi.co,但后来改为 swapi.dev。
解决方案
当请求本身满足一定的一组要求时,浏览器认为该请求是一个“简单”请求:
使用 Content-Type 标头时,仅允许以下值:application/x-www-form-urlencoded、multipart/form-data 或 text/plain
所以我不能用"content-type": "application/json"
。实际上,我认为当您将数据从客户端发送到服务器时,应该使用内容类型。对于简单的 GET 请求,我们通常不会这样做。
所以我应该写:
return fetch(url, {
})
推荐阅读
- vue.js - Vue调用另一个组件文件方法
- terminal - Mac OS 终端显示 [~] ruby 2.7.1p83 $
- java - 使用一个类的最佳方式,其中只有一个更改的对象 - Kotlin/Android/Java
- sockets - JMeter 5.3 - java.net.SocketException:连接重置错误消息
- oracle - 蟾蜍不要把时间还给我
- flutter - 我应该发布参数变化的问题吗
- c# - 编写 If 语句时 C# 中的未知错误
- swiftui - 导航回列表 (SwiftUI) 后,选定列表行的背景保持灰色(选中)。iOS14 + Xcode12
- python - 图像处理:道路提取
- laravel-livewire - 输入值不适用于 Livewire 电线:型号