根据选项请求,角度ajax调用超时,可能存在CORS问题

根据选项请求,角度ajax调用超时,可能存在CORS问题,ajax,angularjs,nginx,cors,Ajax,Angularjs,Nginx,Cors,我有一个web应用程序(www.webapp.com),它运行在不同的服务器上,试图用我的后端rest服务器(api.example.com)进行api调用。我试图通过web浏览器与web应用程序交互,但ajax调用不起作用。例如,尝试向api.example.com/endpoint发出请求 有没有线索知道我在这里遗漏了什么 在Chrome的控制台上,我看到: OPTIONS https://api.example.com/endpoint net::ERR_CONNECTION_TIMED_

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

有没有线索知道我在这里遗漏了什么

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

OPTIONS https://api.example.com/endpoint net::ERR_CONNECTION_TIMED_OUT
OPTIONS https://api.example.com/endpoint [250ms]  
null
在Firefox的控制台上,我得到:

OPTIONS https://api.example.com/endpoint net::ERR_CONNECTION_TIMED_OUT
OPTIONS https://api.example.com/endpoint [250ms]  
null
我正在使用nginx为rest服务器提供服务。nginx.conf的位置部分包含:

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;
     }

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

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

@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;
}

您可以对后端服务器进行设置,使其知道客户端是可信的。处理这些选项是由服务器容器Tomcat/Apache来完成的,没有其他解决方案,而是将客户机的URL专门编码到服务器配置中

不幸的是,我不熟悉nginx,但这里有一个文档讨论了如何设置CORS。 请看这里: