header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, DELETE, PUT");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header('Access-Control-Allow-Headers:x-requested-with,content-type,token');
exit("ok");
}
下面是遇到的另外一种情况,在本地uniapp的代码中nginx中设置跨域请求,访问首页是可以的,但是提交表单又会遇到跨域请求。下面是解决代码:
# 允许的来源(替换为你的前端域名,生产环境避免用 *)
add_header Access-Control-Allow-Origin http://localhost:8080;
# 允许携带凭证(如 Cookie)
add_header Access-Control-Allow-Credentials true;
# 允许的请求方法(包含 POST、OPTIONS 等)
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
# 允许的请求头(根据实际需求添加)
add_header Access-Control-Allow-Headers Content-Type,Authorization;
# 预检请求的缓存时间(减少 OPTIONS 请求次数)
add_header Access-Control-Max-Age 86400;
# 处理预检请求(直接返回 204)
if ($request_method = OPTIONS) {
return 204;
}