WEB 跨域/CORS 配置示例
1、NGINX 配置
server {
listen 80; # 监听的端⼝
server_name localhost; # 域名或ip
location / { # 访问路径配置
#允许跨域请求的域,* 代表所有
add_header 'Access-Control-Allow-Origin' *;
#允许带上cookie请求
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,比如 GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
#允许请求的header
add_header 'Access-Control-Allow-Headers' *;
if ($request_method = 'OPTIONS') {
return204;
}
root /usr/share/nginx/html;# 根⽬录
index index.html index.htm; # 默认⾸⻚
}
error_page 500 502 503 504 /50x.html; # 错误⻚⾯
location = /50x.html {
root html;
}
}
2、JAVA 配置
3、PHP 配置
#入口文件处添加
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: *");
4、NODEJS 配置
4.1、nodejs express 配置
//1.导入模块
const express = require('express')
//2.创建服务器
let app = express()
// 导入一个cors(需要下载:这是给响应头设置res.setHeader("Access-Control-Allow-Origin", "*"))
var cors = require('cors')
app.use(cors())
4.2、nodejs koa2 配置
const cors = require('koa2-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors({
exposeHeaders: ['Authenticate'],
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
跨域异常
Access to XMLHttpRequest at '' from origin '' 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.
WEB 跨域/CORS 配置示例 HTTP跨域解决方案|跨域在线调试|CORS在线调试|JAVA|PHP|nodejs|nginx|Access-Control-Allow-Origin|Access-Control-Allow-Headers|Access-Control-Allow-Methods|1、NGINX 配置|2、JAVA 配置|3、PHP 配置|4、NODEJS 配置|跨域异常|平易在线
WEB 跨域/CORS 配置示例 HTTP跨域解决方案|跨域在线调试|CORS在线调试|JAVA|PHP|nodejs|nginx|Access-Control-Allow-Origin|Access-Control-Allow-Headers|Access-Control-Allow-Methods