我正在尝试使用javascript + CORS访问维基百科
据我所知,维基百科应该支持CORS:http://www.mediawiki.org/wiki/API :Cross-site_requests
我尝试了以下脚本:创建XMLHttpRequest + credential/XDomainRequest,添加一些Http-Headers("Access-Control-Allow-Credentials",...)并发送查询.
http://jsfiddle.net/lindenb/Vr7RS/
var WikipediaCORS=
{
setMessage:function(msg)
{
var span=document.getElementById("id1");
span.appendChild(document.createTextNode(msg));
},
// Create the XHR object.
createCORSRequest:function(url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr)
{
xhr.open("GET", url, true);
}
else if (typeof XDomainRequest != "undefined")
{
xhr = new XDomainRequest();
xhr.open(method, url);
}
else
{
return null;
}
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Origin","*");
return xhr;
},
init:function()
{
var _this=this;
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=Javascript&format=json';
var xhr = this.createCORSRequest(url); …Run Code Online (Sandbox Code Playgroud) 我正在尝试向Wikipedia API发送get请求.我发送请求形式一个角度前端所以我正在尝试使用Heroku CORS Anywhere端点来避免CORS问题.出于某种原因,我仍然得到503响应,表示请求的资源上没有access-control-allow-origin报头.知道为什么会发生这种情况/我还能尝试什么?
我的代码:
import { Injectable } from '@angular/core';
import { Http, Response, } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class RestService {
API_URL: string = 'https://cors-anywhere.herokuapp.com/https://en.wikipedia.org/wiki/';
constructor(private http: Http) { }
public getRandomArticle() : Observable<any> {
return this.http.get(`${this.API_URL}Special:Random`)
.map((res: Response) => res.json())
.catch((err: any) => Observable.throw(err || 'server error'));
}
}
Run Code Online (Sandbox Code Playgroud)