XMLHttp请求无法加载 对预检请求的响应未通过访问控制检查

XMLHttpRequest cannot load Response to preflight request doesn't pass access control check

本文关键字:请求 响应 访问控制 检查 加载 XMLHttp      更新时间:2023-09-26

在我的 Angular 应用程序中,下面是我在本地开发时尝试登录时遇到的错误 (Chrome):

XMLHttpRequest cannot load https://www.tickertags.com/app/api/login. 
Response to preflight request doesn't pass access control check: 
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8100'
that is not equal to the supplied origin.
Origin 'http://localhost' is therefore not allowed access.

来自我的登录控制器的登录函数

function login(credentials) {
    console.log('credentials',credentials);
    AuthFactory.login(credentials).then(function (user) {
        $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
        $scope.setCurrentUser(user);
        if (user.password_reset) {
            $location.path('/password');
        } else {
            $location.path('/tickers');
        }
    }, function () {
        console.log('"Invalid Username/Password"');
        $scope.loginData.message = "Invalid Username/Password";
        $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
    }, function () {
        console.log('"Invalid Username/Password"');
        $scope.loginData.message = "Invalid Username/Password";
        $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
    });
}

AuthFactory.login函数命中托管在生产环境中的 API。我不确定我错过了什么?这就是我的本地主机链接的样子 http://localhost/static/manage/v2/#/login

希望这可以帮助遇到此问题并且无法访问服务器端任何内容的其他人。

解决了我的问题,我试图通过我的 API 调用来登录,即:www.tickertags.com/api/...而不仅仅是/api/...修复它。

要克服 CORS 问题,您必须同时配置前端和后端。

对于前端,当您在初始化时调用 myApp.run() 方法时,您可以配置默认的 HTTP 标头:

$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];

对于后端部分,需要修改请求标头。我不知道你的后端有什么,但我通常在我的本地节点服务器上使用这些。

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
 });