Prepare to design a Restful Api based on Nginx. You need to use DELETE and PUT request methods, and support cross-domain access. Currently, there are local virtual hostshttp://api.zlzkj.com
andhttp://127.0.0.1/api/web
Two test domains.
nginx.conf related cross-domain configuration
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 request
<!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>
Access under http://api.zlzkj.com/
http://api.zlzkj.com/admins/1
You can use the DELETE request method normally
When you visit http://api.zlzkj.com/admins/1
under http://127.0.0.1/api/web/
, you will find that the Request Method is filtered into OPTINOS mode, normally it should be DELETE mode, which caused the server's 405 Method Not Allowed
I have also found some related articles over the wall. It seems that after their Nginx is configured in this way, the DELETE request method can be used normally across domains. However, on my side, it can only be used in the same domain, and the Request Method will be filtered across domains. In OPTINOS mode, a 405 error occurs.
Is it a problem with the Nginx version? Environment configuration problem? I hope you can give me some insights, thank you.
某草草2017-05-16 17:17:58
OPTIONS
请求比较特殊,该方法用于请求服务器告知其支持哪些其他的功能和方法。
在跨域的时候,浏览器会自动发起一个OPTIONS
请求。
当你的服务器响应了OPTIONS
When requesting, there will be a response similar to the following:
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
If your server does not handle the responseOPTIONS
, there will be a response like this:
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
It can be seen that the Allow
response header is missingAllow
响应头
所以,你应该有处理这个OPTIONS
So, you should have a service to handle this
request. This can be done directly with 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;
}
PHPz2017-05-16 17:17:58
$.ajax({
url: 'http://api.zlzkj.com/admins/1',
type: 'DELETE',
dataType: 'JSON',
crossDomain:true
});