首页 > Nginx如何进行跨域配置,才能使用DELETE,PUT请求方法

Nginx如何进行跨域配置,才能使用DELETE,PUT请求方法

背景描述

准备基于Nginx设计一个Restful Api,需要用到DELETE,PUT请求方式,并且要支持跨域访问,目前有本地虚拟主机http://api.zlzkj.comhttp://127.0.0.1/api/web两个测试域。

问题描述

nginx.conf相关跨域配置

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;

ajax请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>
<body>
    Resetful Api设计
    <script src="http://c.csdnimg.cn/public/common/libs/jquery/jquery-1.11.1.min.js"></script>
    <script>
        $.ajax({
            url: 'http://api.zlzkj.com/admins/1',
            type: 'DELETE',
            dataType: 'JSON'
        });
    </script>
</body>
</html>

http://api.zlzkj.com/下访问http://api.zlzkj.com/admins/1可以正常使用DELETE请求方式

http://127.0.0.1/api/web/下访问http://api.zlzkj.com/admins/1会发现Request Method过滤成OPTINOS方式了,正常应该是DELETE方式,引起了服务器的405 Method Not Allowed

翻墙也找过一些相关文章,好像他们的Nginx这样配置后就可以跨域正常使用DELETE请求方式了,而我这边只有在同域下才能使用,跨域就会将Request Method过滤成OPTINOS方式了,就引起了了405错误。
是Nginx版本的问题?环境配置的问题?希望大家能给点见解,谢谢了。


$.ajax({
    url: 'http://api.zlzkj.com/admins/1',
    type: 'DELETE',
    dataType: 'JSON',
    crossDomain:true
});

OPTIONS请求比较特殊,该方法用于请求服务器告知其支持哪些其他的功能和方法。
在跨域的时候,浏览器会自动发起一个OPTIONS请求。
当你的服务器响应了OPTIONS请求的时候,会有类似如下的响应:

Allow → GET,HEAD,POST,OPTIONS,TRACE
Cache-Control → max-age=86400
Connection → keep-alive
Content-Encoding → gzip
Content-Length → 20
Content-Type → text/html
Date → Thu, 30 Jun 2016 04:00:24 GMT
Expires → Fri, 01 Jul 2016 04:00:24 GMT
Server → bfe/1.0.8.14
Vary → Accept-Encoding,User-Agent

如果你的服务器没有处理响应OPTIONS,会有如下的响应:

Connection → keep-alive
Content-Encoding → gzip
Content-Type → text/html
Date → Thu, 30 Jun 2016 04:02:35 GMT
Server → nginx/1.4.6 (Ubuntu)
Transfer-Encoding → chunked

可以看出,缺少了Allow响应头
所以,你应该有处理这个OPTIONS请求的服务,这个可以直接用nginx做,
在配置中,加一下如下的配置:

if ($request_method = 'OPTIONS') { 
add_header Access-Control-Allow-Origin *; 
add_header Access-Control-Allow-Credentials true; 
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; 
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; 
return 204; 
}
【热门文章】
【热门文章】