【发布时间】:2018-06-27 02:28:03
【问题描述】:
提到牛津词典api(https://developer.oxforddictionaries.com)不支持CORS。相反,他们建议让查询到达用户的服务器端应用程序,然后将API请求从用户服务器发送到牛津服务器而不是直接从客户端。所以不可能直接向他们的服务器发送 API 请求。那么,我需要在我的代码中进行哪些更改才能从他们的 api 获取数据。此外,我不想使用代理配置或 CORS 插件或浏览器调整。因为它们会导致安全漏洞,也不能用作永久解决方案。
xyz.service.ts
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from "@angular/common/http";
import {Http, Response} from '@angular/http';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class XyzService {
word: String = "aardvark";
constructor(private _http: HttpClient) {}
private handleError(err: HttpErrorResponse) {
console.log(err.message);
return Observable.throw(err.message);
}
getDictonaryData(name?): any {
if(name){
this.word = name
}
let headers = new HttpHeaders();
headers.append('Accept','application/json');
headers.append('app_id','4eb****91');
headers.append('app_key','7d0740a128***9bbc66907835843d6f');
let myResponse = this._http.get('https://od-
api.oxforddictionaries.com/api/v1/entries/en/'+this.word,{headers: headers
});
return myResponse;
}
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { XyzService } from './xyz.service';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name:string;
dictData:any;
constructor(private _route: ActivatedRoute, private router: Router, private
xyzService: XyzService, ) {}
getData() {
this.xyzService.getDictonaryData(this.name).subscribe(
data => {
this.dictData = data;
console.log(this.dictData);
} ,
error => {
console.log("some error occured");
console.log(error.errorMessage);
}
);
}}
app.component.html
<input id="name" type="text" [(ngModel)]="name"/>
<button (click)="getData()"> Get Data </button>
<div class="row" *ngIf="dictData">
<h2>{{dictData["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]
["definitions"]}}
</h2>
</div>
【问题讨论】:
-
您需要创建自己的 server 端方法(nodejs、php、任何服务器语言),该方法将从远程 url 获取数据。然后在该服务器端方法上实现 CORS(如果需要)
标签: angular