gpt4 book ai didi

javascript - 即使设置了 header , Node 原点也是如此

转载 作者:行者123 更新时间:2023-12-03 03:37:40 24 4
gpt4 key购买 nike

我在同一台服务器上有两个 URL:mydomain.comapi.mydomain.com

现在,在我的 API 中,我添加了以下内容来处理访问来源:

app.use(function (req, res, next) {
// CORS headers
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, x-access-token, Cache-Control, Pragma"
);
next();
});

但是,当我尝试向此 API 发出请求时,我会收到以下错误:

XMLHttpRequest cannot load https://api.mydomain.dk/login. Response topreflight request doesn't pass access control check: No'Access-Control-Allow-Origin' header is present on the requestedresource. Origin 'https://www.mydomain.dk' is therefore not allowedaccess.

我错过了什么?

最佳答案

顺序很重要,您必须在路线之前执行此操作:

Example Code :

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

app.get('/', function(req, res, next) {
// Handle the get for this route
});

app.post('/', function(req, res, next) {
// Handle the post for this route
});

我建议使用cors express 模块。

<小时/>

编辑:

Enable Cors Nodejs Apache

Enabling CORS on apache is a two-step process. First you must create a file with the name .htaccess and add it to the directory where your cross-domain-friendly files are. We recommend you create a new directory for this. The file must contain the following code, (lines 2 and 3 may be optional):

Header always set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

The second step in the process is to enable .htaccess files. Test out the CORS requests and see if they are already working (some installations of Apache come with .htaccess files already enabled). In order to test if it’s working, reload apache (using the command below) and then fire your ajax request at your server.

sudo service apache2 restart

If that worked, you’re done. If not, then you need to add the following code inside the VirtualHosts section of your 000-default.conf in your /etc/apache2/sites-available folder:

Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all

Make sure you replace the /var/www/ with the actual path to your document root. Congrats! You’re done!

关于javascript - 即使设置了 header , Node 原点也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45777159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com