2017-01-12 102 views
1

我是新来的Rest API。我正尝试从我的应用程序调用跨域rest API。 这里是我的代码 -其余API - 405方法不允许

$.ajax({ 
      type: "GET", 
      async: false, 
      url: 'http://xx.xxx.xxx.xx:9003/GetProjectList', 
      contentType: "application/json", 
      dataType: "json", 
      traditional: true, 
      CrossDomain: true, 
      data: { 
       StartDate: '2016-12-20', 
       EndDate: '2017-01-10' 
      }, 
      success: function (data) { 
       alert("Success"); 
       alert(data); 

      }, 

      error: function (xhr, textStatus, errorThrown) { 
       alert("Failed"); 
       alert(xhr); 
       alert(textStatus); 
       alert(errorThrown); 

      } 
     }); 

但我得到的错误作为

OPTIONS http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10 405 (Method Not Allowed) 

XMLHttpRequest cannot load http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64207' is therefore not allowed access. The response had HTTP status code 405. 

我在这里缺少什么?任何代码或配置?

如果我直接从浏览器或邮递员打那个URL,它的工作正常。但它不适用于应用程序。

+0

这是基本的CORS错误。您应该在响应头中设置必需的CORS头。有很多SO回答可用于此。顺便说一句,你的服务是web-api还是wcf-rest?您不应该将两个标签添加在一起 – Developer

+0

您只需要允许CORS。知道,它并不总是工作! –

+0

为什么在GET请求上设置Content-Type? – Quentin

回答

0

我认为这个问题是一个CORS问题(有时405也意味着你正在调用错误的HTTP动词的API)..但是读你的例外,它看起来像一个CORS问题..试试这个:

using Goocity.API; 
using Microsoft.Owin; 
using Microsoft.Owin.Cors; 
using Owin; 

[assembly: OwinStartup("API", typeof(Goocity.API.Startup))] 

    namespace Goocity.API 
    { 
     public partial class Startup 
     { 
      public void Configuration(IAppBuilder app) 
      { 
       #region TO UNCOMMENT WHEN IS IN PRODUCTION 
       //var corsPolicy = new CorsPolicy 
       //{ 
       // AllowAnyMethod = true, 
       // AllowAnyHeader = true, 
       // SupportsCredentials = true, 
       // Origins = { "http://www.yoursite.it" } 
       //}; 

       //app.UseCors(new CorsOptions 
       //{ 
       // PolicyProvider = new CorsPolicyProvider 
       // { 
       //  PolicyResolver = context => Task.FromResult(corsPolicy) 
       // } 
       //}); 
       #endregion TO UNCOMMENT WHEN IS IN PRODUCTION 

       app.UseCors(CorsOptions.AllowAll); 
       ConfigureAuth(app); 

      } 
     } 
    } 

尝试将其放入您的startUp文件并安装Microsoft.Owin.Cors nuget包