如何解决我的网站与相同域的网站之间的CORS问题?

问题描述

我有一个网站https://example.com,该网站在加载时应该从另一个网站https://subdomain.example.com:8080获取数据,但是显然,我的请求被阻止了。附件是我在浏览器的“网络”标签中看到的内容。该请求从浏览器端发送到subdomain.example.com的代理。我需要什么CORS标头?我不熟悉CORS,并且尝试过在线阅读文档和示例,但无济于事。

my CORS issue

解决方法

https://example.com被阻止,因为https://subdomain.example.com:8080中不允许。

拥有https://subdomain.example.com:8080的人,必须在允许的服务器原始位置添加https://example.com

https://example.comhttps://subdomain.example.com:8080在CORS方面都被区别对待。

例如,在nodejs表达代码中,这就是添加CORS和允许原始服务器的方式。

在我的示例中,http://localhost:8080将替换为https://example.com

app.use(function (req,res,next) {
    res.header("Access-Control-Allow-Origin","http://localhost:8080");
    res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
    next();
});

完整代码-


const bodyParser = require('body-parser')
const path = require('path');
const express = require('express');
const app = express();
const modelRoute = require('./model');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

app.use(express.static('dist'));

app.use(function (req,Accept");
    next();
});


app.get('/api/getData',modelRoute.getData);
app.post('/api/postData',modelRoute.postData);

app.listen(process.env.PORT || 8080,() => console.log(`Listening on port ${process.env.PORT || 8080}!`));

在Nginx端启用了两个级别的CORS,在https://subdomain.example.com上启用了另一个级别。

首先,您需要在全局级别或本地服务器部分的nginx.conf中添加以下标头。 nginx.conf可能已经有此标头,因此您也需要添加它。

add_header Access-Control-Allow-Origin https://example.com;

更重要的是,首先,您需要查看什么以及如何配置nginx.conf。基于此,如果在nginx.conf中启用了CORS,也可以在/ location部分中添加此标头。

这是一个样本

# local node.js server
upstream websocket {
    server 127.0.0.1:3000;
}

server {
    server_name ...;
    # ...;

    # add the header here
    add_header Access-Control-Allow-Origin https://example.com;

    location /path/ {
       
        proxy_hide_header 'Access-Control-Allow-Origin';
    }
}

由于其他标头以及nginx端,该请求也可能被阻塞。如果以上都不起作用。您需要查看nginx.conf有哪些额外的头文件。对于exm-

add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
 add_header 'Access-Control-Allow-Credentials' 'true';
 add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Range,Range';
 add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

这很容易配置,但可能需要一些时间进行实验。

您也可以查看下面的线程。它可以帮助您了解更多。

NGINX Reverse Proxy and Access-Control-Allow-Origin issue

How to enable CORS in Nginx proxy server?

如果nginx.conf看起来不错并且仍然不起作用,那么只有您跳到子域网站配置。这样可以节省您的时间。