例如客户端的域名是 www.redis.com.cn , 而请求的域名是 www.264.cn 如果直接使用ajax访问,会有以下错误
XMLHttpRequest cannot load http://www.264 .cn/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.redis.com.cn' is therefore not allowed access.
在服务器页面的Response header中加入如下内容,可以实现POST跨域。
header ('Access-Control-Allow-Origin:*' );
header ('Access-Control-Allow-Methods:POST' );
header ('Access-Control-Allow-Headers:x-requested-with,content-type' );
Access-Control -Allow -Origin :* 表示允许任何域名跨域访问
如果需要指定某域名才允许跨域访问,只需把Access-Control -Allow -Origin :* 改为Access-Control -Allow -Origin :允许的域名
例如:header ('Access-Control-Allow-Origin:http://www.redis.com.cn' );
server{
listen 8099 ;
server_name wdm. test. cn ;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control -Allow -Origin "$http_origin" ;
add_header Access-Control -Allow -Methods "POST, GET, PUT, OPTIONS, DELETE" ;
add_header Access-Control -Max -Age "3600" ;
add_header Access-Control -Allow -Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization" ;
add_header Access-Control -Allow -Credentials "true" ;
add_header Content-Length 0 ;
add_header Content-Type text/plain;
return 201 ;
}
add_header 'Access-Control-Allow-Origin' '$http_origin' ;
add_header 'Access-Control-Allow-Credentials' 'true' ;
add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS' ;
add_header 'Access-Control-Allow-Headers' 'Content-Type,*' ;
proxy_pass http:
}
}