提到牛津词典api(https://developer.oxforddictionaries.com)不支持CORS。相反,他们建议使查询到达用户的服务器端应用程序,然后将API请求从用户的服务器发送到oxford的服务器,而不是直接从客户端。因此,不可能直接向其服务器发送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>
答案 0 :(得分:0)
对于节点服务器
步骤-1:安装 URL
npm install url
第2步:保存脚本
script.js
var https = require('https');
var http = require('http');
var url = require('url');
var my_app_id;
var my_app_key;
var mainRes;
// Recieve get request from client
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
mainRes = res;
var parsedUrl = url.parse(req.url, true); // true to get query as object
var params = parsedUrl.pathname;
my_app_id = JSON.stringify(req.headers.app_id).replace(/\"/g, "");
my_app_key = JSON.stringify(req.headers.app_key).replace(/\"/g, "");
var word_id = params.substring(1);
if (word_id && my_app_id && my_app_key) {
// Proper Request
var options = {
host: 'od-api.oxforddictionaries.com',
port: 443,
path: '/api/v1/entries/en/'+word_id,
method: 'GET',
headers: {
'app_key' : my_app_key,
'app_id' : my_app_id
}
};
console.log("Start");
var x = https.request(options,function(res){
console.log("Connected");
var responseString = "";
res.on('data',function(data){
responseString += data;
});
res.on("end", function () {
console.log(responseString);
mainRes.end(responseString);
// print to console when response ends
});
});
x.end();
} else {
res.end("Request not proper");
}
}).listen(1337, '127.0.0.1');
第3步:运行
node script.js
第4步:发送带有标头的Get请求
示例:对于单词“ hello” 获取请求应为http://yourdomain.com:1337/hello 或http://yourserverip:1337/hello 带有标题app_id和app_key