gpt4 book ai didi

java - 如何使用 Angular 6 绕过跨源错误(Firefox CORS 错误、Chrome 预检错误)

转载 作者:行者123 更新时间:2023-12-02 03:29:23 25 4
gpt4 key购买 nike

我正在开发一个前端,用作rest-api 的客户端。使用 Angular 6。

问题是,当我使用 HttpClient 发送 POST 请求时,出现此跨源错误。我的代码:

服务:

export class ApiConfigLogin {
constructor(private http: HttpClient,
private dataSrvc: DataService) {}

private _url = this.dataSrvc.getMainUrl() + '/sec-login';

private options = {
headers: new HttpHeaders().set('Content-Type', 'application/json')
};
getResults(reqbody): Observable < ApiConfigLoginInterface > {
console.log(this._url);
return this.http.post < ApiConfigLoginInterface > (this._url, reqbody, this.options);
}
}

组件.ts

this._ApiConfigLogin.getResults(body)
.subscribe(data => {
this.enableForms();
if (data.status === 401) {
this.lowerMessage = data.message;
} else {
console.log(1);
}
});

在火狐浏览器中:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8888.8888.8888.8888:8888/address/sec-login. (Reason: CORS request did not succeed).

在谷歌浏览器中:

Failed to load http://8888.8888.8888.8888:8888/address/sec-login: Response for preflight is invalid (redirect)

我已经测试了允许对我的浏览器进行控制扩展。很高兴知道我有一个内容类型 header :

最佳答案

有很多方法可以解决这个问题;请参阅this在 GitHub 上了解如何处理 CORSS 客户端:

JSONP

WARNING: This isn't allowed on every API and may break when calling certain APIS

You can bypass CORS in production using JSONP which stands for JSON with Padding and is kinda also a 'hack'. But it is a widely used hack which many APIs support. You are not sending a pure JSON-request but you are wrapping your data in a function that gets evaluated. JSONP explained in the link below:

或使用代理:

Proxy

WARNING: Great services, but you are dependent on these services to work, if they break or go down, so does your app

You can use a service that proxies your request and automatically enable CORS for your:

然后,您必须通过将这些 URL 之一添加到您的请求来调用您的 API,例如:

关于java - 如何使用 Angular 6 绕过跨源错误(Firefox CORS 错误、Chrome 预检错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52263286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com