如何从Angular7前端传递API识别上的CORS问题?

问题描述 投票:0回答:1

我正在使用Angular 7开发前端。我需要通过发布请求使用我的凭据向API进行身份验证。当我发出请求时,我收到:

zone-evergreen.js:2952 OPTIONS https://[...]/oauth/token?grant_type=client_credentials 400

Access to XMLHttpRequest at 'https://[...]/oauth/token?grant_type=client_credentials' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://[...]/oauth/token?grant_type=client_credentials", ok: false, …}

我无法更改API,我想知道如何从角度解决CORS问题。

APIservice.ts:

const API_URL = environment.apiUrl;
@Injectable({
  providedIn: 'root'})
export class ApicallService {constructor(private httpclient: HttpClient) { }

   createToken() {
         const credentials = { 
          grant_type: 'client_credentials',
          client_id: '***',
          client_secret: '+++',}
        const httpOptions = {
          headers: new HttpHeaders({
            'Access-Control-Allow-Origin':'*',
            'content-type': 'application/x-www-form-urlencoded'}) }; 

          return this.httpclient
          .post(API_URL + '/oauth/token?grant_type=client_credentials', credentials, httpOptions )
            .pipe(map(response => console.log(response))) } 

我的token.component.ts:

export class TokenComponent {

   //define a component property called bearer to expose the Bearer array for binding.
  bearer: Bearer[];

   constructor(private http: HttpClient,private callApi: ApicallService) {}

    //call the api by post to identifie
 getBearer(): void{

  this.callApi. createToken() 
        .subscribe();}

我还尝试配置代理。我的Proxy.conf.json:

 {
     "/oauth/*": {
         "target": "http://localhost:4200",
         "secure": false,
         "logLevel": "debug",
         "changeOrigin": true,
         "pathRewrite": {
             "^/oauth": ""
         }
     }}

angular.json:

 "serve": {
           "builder": "@angular-devkit/build-angular:dev-server",
           "options": {
           "browserTarget": "angularjs-wabapp:build",
           "proxyConfig": "src/proxy.conf.json"
api proxy cors angular7 basic-authentication
1个回答
0
投票

Cors基本上在服务器上,可以接受来自任何来源的任何请求。

[您必须更改API才能允许跨源请求只有这样才能起作用。

© www.soinside.com 2019 - 2024. All rights reserved.