gpt4 book ai didi

javascript - 维基百科 API 上的 CORS 错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:31:11 25 4
gpt4 key购买 nike

我对如何在 React 中处理维基百科 API 调用感到有点困惑。我一直遇到这个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource(...)

现在,我在提交表单时运行一个操作,该表单采用表单输入值并将其插入到 Wikipedia api URL 中。我已经尝试过使用 JSONP,但我真的不想使用它,因为我听说它 super hacky。

Action /index.js

import axios from 'axios';

const WIKI_URL = "https://en.wikipedia.org/w/api.php?action=query&format=jsonp&list=search&titles=";
const FETCH_ARTICLES = 'FETCH_ARTICLES';

export function fetchArticles(term) {
const url = `${WIKI_URL}${term}`;
const request = axios.get(url);

return {
type: FETCH_ARTICLES,
payload: request
}

如有必要,我绝对可以添加更多代码,但据我所知,这就是问题所在。

编辑:如果我必须使用 JSONP,我仍然无法使用。我相信 axios 不支持 JSONP,是否有更好的库可以使用?为什么有些 API 会出现跨源引用错误,而有些则不会?

最佳答案

删除 format=jsonp 并将 origin=* 添加到 WIKI_URL 值中的查询参数:

const WIKI_URL = "https://en.wikipedia.org/w/api.php?origin=*&action=query…";

参见 the CORS-related docs for the Wikipedia backend :

For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.

format参数而言,JSON输出是默认的,所以你不需要指定。

关于javascript - 维基百科 API 上的 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42283282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com