gpt4 book ai didi

javascript - 由于 http 导致 CORS 不匹配

转载 作者:行者123 更新时间:2023-12-02 18:49:53 25 4
gpt4 key购买 nike

我不明白为什么会收到此错误。

sub.domain.app/:1 XMLHttpRequest cannot load http://domain.app/wc-api/v3. The 'Access-Control-Allow-Origin' header contains the invalid value 'sub.domain.app'. Origin 'http://sub.domain.app' is therefore not allowed access.

站点domain.app是一个wordpress安装,sub.domain只是静态html。当我尝试通过 ajax (vue-router) 获取时,会发生错误。

这两个域都位于宅基地。我已经设置了 nginx 以允许子域执行 CORS 请求。

location / {
try_files $uri $uri/ /index.php?$query_string;
add_header 'Access-Control-Allow-Origin' "http://sub.domain.app";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

我希望比我聪明的人能帮我解决这个问题。提前致谢!

最佳答案

您似乎希望允许对主域子域的请求。 CORS specification不允许在单个 header 中这样做。确切的域或“*”。您必须动态检查域并在 header 中设置

使用 NGINX:

 server {

root /path/to/your/stuff;

index index.html index.htm;

set $cors "";

if ($http_origin ~* (.*\.domain.com)) {
set $cors "true";
}

server_name domain.com;

location / {

if ($cors = "true") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
}


if ($request_method = OPTIONS) {
return 204;
}

}
}

More here .

使用 PHP

检查 $_SERVER['HTTP_HOST'] 并在其中搜索您所需的(子)域,然后使用 PHP 有条件地设置 CORS header 。

所以,像这样:

$allowed_hosts = array('sub.domain.app', 'domain.app');

if (in_array($allowed_hosts, $_SERVER['HTTP_HOST'])) {
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_HOST']);
}

关于javascript - 由于 http 导致 CORS 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34302021/

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