前段跨域问题 check: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.

跨域报错:cess to XMLHttpRequest at 'http://mycelium.test/api/PluginController/getVoiceConfig' from origin 'http://localhost:63343' 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.

看到这哦吼跨域了 第一想法 nginx 添加跨域头和php入口文件加上跨域头(业务需要只允许/api/PluginController的支持跨域)

location /api/PluginController {
  add_header 'Access-Control-Allow-Origin' '*';

  xxxxx............
}

前段跨域问题 check: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource._第1张图片

 

报错依旧。感觉不对都给了咋还报错呢。查下nginx瞅瞅

 请求进来了access.log  状态都是500 一查长知识了   跨域请求浏览器会发送两次请求,预请求通过了才是真正的数据请求

前段跨域问题 check: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource._第2张图片

前段跨域问题 check: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource._第3张图片 最后找到解决方案直接预请求返回 2xx

 

location /api/PluginController {
  add_header 'Access-Control-Allow-Origin' '*';
  if ($request_method = 'OPTIONS') {
        return 200;
    }
  xxxxx............
}

 到这错误又变了

cess to XMLHttpRequest at 'http://mycelium.test/api/PluginController/getVoiceConfig' from origin 'http://localhost:63343' has been blocked by CORS policy: Request header field x-mc-checksum is not allowed by Access-Control-Allow-Headers in preflight response.

因为业务需要自己定义了几个特殊的Header字段导致不允许,加个配置通过下

location /api/PluginController {
  add_header 'Access-Control-Allow-Origin' '*';
if ($request_method = 'OPTIONS') {
        return 200;
    }
add_header 'Access-Control-Allow-Headers' 'x-mc-from,x-mc-checksum,x-mc-product,access-control-allow-origin,User-Agent,Cache-Control,Content-Type,Range';

  xxxxx............
}

到此问题处理完毕

最后给个建议:安全起见不建议Access-Control-Allow-Origin直接为 ‘*’ 最好是指定域名或二级域名

你可能感兴趣的:(nginx,运维)