【问题标题】:angular ajax call timing out on OPTIONS request, possible CORS issueOPTIONS请求的角度ajax调用超时,可能的CORS问题
【发布时间】:2015-01-24 08:24:03
【问题描述】:

我有一个在 不同 服务器上运行的 Web 应用程序 (www.webapp.com),它试图通过我的后端休息服务器 (api.example.com) 进行 api 调用。我正在尝试通过 Web 浏览器与 Web 应用程序交互,但 ajax 调用不起作用。例如,尝试向 api.example.com/endpoint 发出请求。

知道我在这里缺少什么吗?

在 Chrome 的控制台上,我得到:

OPTIONS https://api.example.com/endpoint net::ERR_CONNECTION_TIMED_OUT

在 Firefox 的控制台上,我得到:

OPTIONS https://api.example.com/endpoint [250ms]  
null

我正在使用 nginx 为其余服务器提供服务。 nginx.conf 的 location 部分包含:

location /{
     proxy_pass http://127.0.0.1:5000;

     add_header 'Access-Control-Allow-Header' 'Origin, Content-Type, Accept, Authorization';
     add_header 'Access-Control-Allow-Methods' 'POST, GET, OPTIONS';
     add_header 'Access-Control-Allow-Origin' 'http://example.com';
     if ($request_method = 'OPTIONS') {
         add_header 'Access-Control-Allow-Origin' 'http://www.webapp.com';
         add_header 'Access-Control-Allow-Methods' 'POST, GET, OPTIONS';
         add_header 'Access-Control-Max-Age' '1728000';
         add_header 'Content-Type' 'text/plain; charset=UTF-8';
         return 200;
     }

【问题讨论】:

    标签: ajax angularjs nginx cors


    【解决方案1】:

    我认为这份文件可以帮助到你

    https://github.com/angular/angular.js/issues/1972enter link description here

    我以前在跨域 api 调用中遇到过这个问题 .. angular 在调用后发送一个选项调用,它等待一个成功的选项请求。我所做的是我创建了一个选项处理程序,它也返回成功 ..我不是确定这是当前的方式,但它可以帮助我解决这个问题

    @POST
    @Path("createNote")
    @Produces(MediaType.APPLICATION_JSON)
    public ResponceMsg createNotePost(@FormParam("subject") String subject,
               @FormParam("description") String description,
               @FormParam("requestId") int requestId){
    
        requestProcess.createNewNote(requestId,subject,description);
        return new ResponceMsg();
    }
    
    @OPTIONS
    @Path("createNote")
    @Produces(MediaType.APPLICATION_JSON)
    public Void createNote(){
        return null;
    }
    

    【讨论】:

      【解决方案2】:

      您的后端服务器可以设置为知道客户端是可信任的。处理选项是由服务器容器执行的,Tomcat / Apache 并且没有其他解决方法,然后专门将客户端的 URL 编码到服务器配置中。

      不幸的是,我对 nginx 不熟悉,但这里有一篇讨论设置 CORS 的文档。 见这里:http://enable-cors.org/server_nginx.html

      【讨论】:

        猜你喜欢
        • 2018-11-19
        • 2015-02-20
        • 2015-03-01
        • 2017-05-14
        • 2022-06-17
        • 2014-04-09
        • 2017-10-16
        • 1970-01-01
        • 2022-01-21
        相关资源
        最近更新 更多