请求出现 Access to XMLHttpRequest at 'xx'

魔众文库系统 / 文档中心
文档中心
开发教程
安装常见问题

在 uniapp 前端页面请求时出现类似如下错误

Access to XMLHttpRequest at 'https://example.com/api/mtiku/config' from origin 'http://localhost:20000' 
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个通常是由于跨域请求导致的,需要在 http 服务器添加跨域相关头信息。

宝塔服务器在 网站设置 → 站点修改 → 伪静态 处添加。

Nginx配置

server {
    
    // 其他配置
    
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers *;
    add_header Access-Control-Expose-Headers *;

    location / {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers *;
        if ($request_method = 'OPTIONS') {
            return 200;
        }
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    // 其他配置
}

Apache配置

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header set Access-Control-Allow-Headers "*"
    Header set Access-Control-Expose-Headers "*"
    Header always set Access-Control-Allow-Credentials "true"
</IfModule>
QQ
微信
公众号
客服