Wikipedia API的CORS错误 [英] CORS Error on Wikipedia API

查看:61
本文介绍了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.

这篇关于Wikipedia API的CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆