Angular 13:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

Cha*_*bes 5 opera swagger-node-express visual-studio-code angular

有人可以帮助我吗?我的 CORS 政策有问题,而且我无法访问网站的后端。

operaGX 导航控制台

这是我在后端(node.js)中使用的代码:

app.use(cors({
  Access_Control_Allow_Origin: "*",
  origin:"*",
  methode:['GET','POST','PATCH','DELETE','PUT'],
  allowedHeaders:'Content-Type, Authorization, Origin, X-Requested-With, Accept'

})); 

Run Code Online (Sandbox Code Playgroud)

这是前端(我使用Angular 13)导入API的代码:environment.ts

export const environment = {
  production: false,
  serverURL: 'http://localhost:3000/api/'
};

Run Code Online (Sandbox Code Playgroud)

我也尝试过这段代码,但它不起作用:

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

Run Code Online (Sandbox Code Playgroud)

Mic*_*ely 3

确保您有正确的进口:

var cors = require('cors')

var app = express()
Run Code Online (Sandbox Code Playgroud)

并使用:

app.use(cors()) // this uses default values
Run Code Online (Sandbox Code Playgroud)

或者将您的代码更改为:

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
Run Code Online (Sandbox Code Playgroud)

在生产中请小心使用“*”作为 Access-Control-Allow-Origin。仅将此更改回允许连接到您的 API 的客户端。

如果这没有帮助,请尝试设置代理请求以在 Angular 中启用 CORS:在应用程序的 src 文件夹中,创建一个名为proxy.conf.json. 这是一个 JSON 文件,其中包含代理服务器的配置。在这里,我们将告诉 Angular 应用程序充当另一个服务器,接受 API 调用并将它们转移到 http://localhost:3000。

在 proxy.conf.json 文件中,添加以下代码:

{
    "/api": {
        "target": "http://localhost:3000",
        "secure": false
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,通知 Angular 有关此代理配置的信息。我们可以通过在 angular.json 文件中添加 proxyConfig 选项来做到这一点:

...
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json"
}
Run Code Online (Sandbox Code Playgroud)