角度 - 包括标头文件



>我必须在我的项目中包含头文件以进行身份验证,但是当我尝试包含它时,它会给出错误 错误:无法加载 https://od-api.oxforddictionaries.com/api/v1/entries/en/hi:请求的资源上不存在"访问控制允许源"标头。因此,不允许访问源"http://localhost:4200"。响应具有 HTTP 状态代码 403。

xyz.service.ts

@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 Headers();
headers.append('Accept', 'application/json');
headers.append('app_id', '*****');
headers.append('app_key', '7d0740a12*******bc66907835843d6f');

let myResponse = this._http.get('https://od- 
api.oxforddictionaries.com / api / v1 / entries / en / ' + this.word);
return myResponse;
}
}

app.comoonent.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>

牛津词典 API 目前不支持 CORS(跨源资源共享(。

相反,他们建议使查询到达用户的服务器端应用程序,然后将API请求从用户的服务器发送到牛津的服务器,而不是直接从客户端发送。

因此,不可能直接向其服务器发送 API 请求。

管理员在牛津论坛讨论中提到了它。

但是您可以轻松地通过服务器绕过您的请求。

对于 Apache 中的 php 实现

使用 GuzzleHttp 实现简单的 PHP

对于节点服务器

使用请求或 Axios 包
,我为节点服务器实现添加了一个解决方案。 你可以在这里找到它

但我建议不要使用 CORS 插件或浏览器调整。因为它们会导致安全漏洞,也不能用作永久解决方案

你可以这样尝试吗

let headers = new HttpHeaders();
headers.set('Accept','application/json');
headers.set('app_id','4ebde091');
headers.set('app_key','7d0740a128b7e39bbc66907835843d6f');
let myResponse = this._http.get('someurl',{
headers: headers
});
let headers = new Headers();

应该是

let headers = new HttpHeaders();

由于Headers现已弃用,因此您需要改用HttpHeaders

欲了解更多信息,请阅读 这里 -

  • https://angular.io/guide/http#adding-headers
  • https://www.concretepage.com/angular-2/angular-httpclient-get-example#parameters

您可以尝试此解决方案

您正在从本地主机访问实时API,因此域是不同的。

您可以将其添加到扩展Access-Control-Allow-Origin

智能扩展并保持开启

您必须安装扩展才能解决此问题。
1.如果您在这里使用chrome浏览器"Moesif Origin & CORS Changer"扩展
2.如果您使用的是Firefox浏览器,则可以从此处安装

最新更新