CORS策略已阻止从来源“ https://my.domain.fr”访问“ https://my.domain.fr/api/login”处的XMLHttpRequest

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

我知道这个问题是已知的,但是在发布此问题之前,我已经尝试过谷歌搜索。

前端是Angular 7,后端是Nodejs。

我们实际上在Prod中出现此错误,并且没有任何作用:错误是随机发生的,并且没有进行更新,有时所有查询都被阻止,有时一切都像超级按钮一样。

在Angular中,我创建了一个看起来像这样的HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';


@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(public authService: AuthService) { }


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true, //added for cors policy

            setHeaders: {
                att: "value"
            }
        });

        return next.handle(request);
    }
}

并且在后端(Nodejs + Express):

...

whiteList = ["http://localhost:4210",
        "http://localhost:4200",
        "http://localhost:4100",
        "https://sub1.domain.fr",
        "https://www.domain.fr",
        "https://sub2.domain.fr"]

    var corsOptions = {
        origin: allowOrigins,
        credentials: true
    }

    app.use(cors(corsOptions))
...

function allowOrigins(origin, callback) {
    if (origin && origin.endsWith("xxxxxxx") || whiteList.indexOf(origin) >= 0) {
        return callback(null, true)
    }
    else {
        return callback(null, false)
    }
}

和错误:

Access to XMLHttpRequest at 'https://api.domain.fr/api/login' from origin 'https://sub1.domain.fr' 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.

谢谢,

node.js angular cors cross-domain policy
1个回答
0
投票

这里是后端日志的快照:

enter image description here

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