Wikipedia API的CORS错误
我对如何处理Wikipedia api调用感到有些困惑。我一直遇到这个错误:
I am a little confused about how to handle a wikipedia api call in react. I keep running into this error:
跨域请求被阻止:同源策略禁止读取远程资源(...)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource(...)
现在,我正在提交表单时执行操作,该表单接受表单输入值并将其插入Wikipedia api URL 。我已经尝试过使用JSONP,但是我真的不希望使用它,因为我听说它是超级hacky。
Right now, I am running an action upon submitting a form, the form takes the form input value and inserts that into the Wikipedia api URL. I have tried using JSONP, but I really would prefer not to use that since I have heard it is super hacky.
actions / index.js
actions/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
}
如果有必要,我当然可以添加更多代码,但是据我所知,这就是问题所在。
I can definitely add more code if necessary, but from what I can tell, this is where the problem lies.
编辑:如果我必须使用JSONP,但仍然无法使用。我相信axios不支持JSONP,会有更好的库吗?为什么某些API会有跨源引用错误,而另一些API没有?
edit: If I had to use JSONP, I still have not been able to. I believe that axios does not support JSONP, would there be a better library to use? Why do some APIs have a Cross Origin Reference Error while others do not?
Drop format = jsonp
并在WIKI_URL值中的查询参数中添加 origin = *
:
Drop format=jsonp
and add origin=*
to the query params in the WIKI_URL value:
const WIKI_URL = "https://en.wikipedia.org/w/api.php?origin=*&action=query…";
请参见 Wikipedia后端的CORS相关文档:
对于匿名请求,可以将
原始
查询字符串参数设置为*
,这将允许来自任何地方的请求。
For anonymous requests,
origin
query string parameter can be set to*
which will allow requests from anywhere.
就 format
参数而言,JSON输出是默认设置,因此我认为您不需要指定。
As far as the format
param, JSON output is the default, so I think you don’t need to specify that.