javascript - IIS7.5下的RESTful不能跨域PUT和POST
PHP中文网
PHP中文网 2017-04-11 12:45:39
0
1
795

用Postman测试成功,但是在自己写的jQuery代码中测试失败
可以Get,但是不能PUT和POST

IIS7.5中web.config已经做了如下设置

<system.webServer>
    <httpProtocol> 
      <customHeaders> 
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" /> 
        <add name="Access-Control-Allow-Headers" value="X-Requested-With" /> 
        <add name="Access-Control-Allow-Origin" value="*" /> 
      </customHeaders> 
    </httpProtocol> 
</system.webServer>

jQuery代码

$.ajax({
    url: 'http://xxx.xxx.xxx.xxx:nnnn/api/apps/791',
    type: 'PUT',
    data: '{"Name": "Tom"}',
    dataType: 'json',
    contentType: 'application/json',
    crossDomain: true,
    beforeSend: function( xhr ) { 
        xhr.setRequestHeader('X-Requested-With', 'jQuery'); 
    },
    success: function( response ) {
        console.log('ok');
    }
});

浏览器 Chrome 53

General
Request URL:http://XXX.XXX.XXX.XXX:10088/api/apps/791
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:XXX.XXX.XXX.XXX:10088


Response Headers
Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Methods:GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:PUT,GET
Cache-Control:no-cache
Content-Length:66
Content-Type:application/json; charset=utf-8
Date:Tue, 13 Sep 2016 02:00:41 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET


Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2
Access-Control-Request-Headers:content-type, x-requested-with
Access-Control-Request-Method:POST
Connection:keep-alive
Host:XXX.XXX.XXX.XXX:10088
Origin:http://XXX.XXX.XXX.YYY:7788
Referer:http://XXX.XXX.XXX.YYY:7788/jqdebug.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
迷茫

自问自答。
答案来自这篇文章:
Vue.js——基于$.ajax实现数据的跨域增删查改
这是大侠keepfool的vue.js系列文章之一,强烈推荐!

我的这个REFTful服务端是用VS2013 ASP.Net Web API 2写的,它有一个插件叫Microsoft.AspNet.WebApi.Cors可以很方便得设置CORS
需要注意的是如果用了这个插件,那么web.config中的以下代码要删除

<system.webServer>
    <httpProtocol> 
      <customHeaders> 
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" /> 
        <add name="Access-Control-Allow-Headers" value="X-Requested-With" /> 
        <add name="Access-Control-Allow-Origin" value="*" /> 
      </customHeaders> 
    </httpProtocol> 
</system.webServer>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template