首页 > 解决方案 > 从本地使用 auth api 时出现意外的 CORS 策略错误

问题描述

首先,我在云上的 ubuntu 服务器上运行了一个后端 RESTapi(完美运行 100%)。

而且我还有一个在同一台服务器上运行的前端 Web 应用程序(也可以正常工作),我可以使用登录系统和所有这些东西。

现在我的问题:出于开发目的,我在我的计算机上本地部署前端,但我仍然希望在云端连接到我的后端,而不是在本地部署后端。

现在的问题是,当我使用本地计算机的身份验证时,我收到此错误:

Access to fetch at 'http://ip-adress-to-the-backend-at-the-cloud:5000/api/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://*:3000' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

问题是:直到上周,它在我的计算机上本地使用 webapp 时完美登录。现在我对我的“.env”文件、“server.js”和“routes.js”文件进行了一些更改,它不工作。

奇怪的是,我尝试从这些文件中删除更改,但仍然无法正常工作。

这是我的 .env 文件:

 APP_PORT=*****
DB_HOST=*****
DB_USER=*****
DB_PASSWORD=******
DB_NAME=******
JWT_SECRET=******
JWT_KEYSECRET=*******
ALLOWED_ORIGIN=http://ipadress_to_both_the_frontend_and_backend:3000

这是我的 server.js:

const express = require('express'); 
const app = express();
require('dotenv').config();

if(process.env.JWT_SECRET == undefined || process.env.JWT_KEYSECRET == undefined){
    console.log("Fatal error: Secret is not set")
    process.exit(1);
}


require('./startup/routes')(app)
require('./startup/database')

app.listen(process.env.APP_PORT, () => {
    console.log("Server is running: " + process.env.APP_PORT);
})

和我的 routes.js:

require('dotenv').config(); 
const users = require('../api/user/user.router')
const keys = require('../api/keys/keys.router')
const equipmentType = require('../api/equipmenttypes/equipmenttype.router');


const auth = require('../api/authentication/auth.router')
const helmet = require('helmet')
const express = require('express')

module.exports = function (app) {
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    app.use(express.static('public'))

    app.use(helmet.xssFilter())
    app.use(helmet.frameguard())
    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGIN);
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, x-auth-token, x-api-key');
        res.setHeader('Access-Control-Allow-Credentials', true);
        next();
    })

    app.use('/api/user', users)
    app.use('/api/auth', auth)
    app.use('/api/key', keys)
    app.use('/api/equipmenttypes', equipmentType)

}

标签: node.js

解决方案


解决方案很简单,我在 env 文件中更改了这一行:

ALLOWED_ORIGIN=*

不,这不是一件好事,而且根本不安全,但是现在我可以从 localhost 访问后端 api,并且可以优化我的工作。


推荐阅读