2016-05-23 29 views
1

我正在使用MEAN Stack编写Web应用程序,并且遇到无法解决的问题,无论我尝试或搜索什么。请求的资源上没有“Access-Control-Allow-Origin”标头

我想用ExpressJS登录使用护照/护照-Facebook。如果我在我的浏览器的URL中写入localhost/api/auth/facebook,一切运行良好。

但是,如果我在我的HTML代码中创建了一个像这样的代码<a href="/api/auth/facebook">Login with Facebook</a>,它会将我带到我的404 page(请参见下面的nginx)。 如果我尝试使用角度方式,例如<button ng-click="login_fb()">Login with Facebook</button>,则会出现No 'Access-Control-Allow-Origin' header is present on the requested resource.错误。

我相信,我应该使用<a href="...">元素,但我觉得我的nginx的脚本阻止它,因为我启用了CORS我的服务器的NodeJS上,与此:

server.all('/*', function (req, res, next) { 
    res.header('Access-Control-Allow-Origin', '*'); 
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type"); 
    next(); 
}); 

我会离开我的nginx的剧本太(忽略内部的“<”块和“>”):

worker_processes 4; 

events { 
    worker_connections 1024; 
} 

http { 

    upstream backend { 
     server 127.0.0.1:8080; 
    } 

    # To optimize the response of static files 
    sendfile on; 

    server { 
     # Listen to normal port 
     listen  80; 

     # Let through files like CSS, JPG, JS, ... 
     include mime.types; 

     # Alias for this server 
     server_name <my-domain>; 

     # Where the HTML files are located 
     root <my-folder>; 

     # Route for API calls 
     location /api/ { 
      proxy_pass http://backend; 
     } 

     # Route for the index 
     location ~ ^/*$ { 
      index index.html index.htm; 
     } 

     # Route for 404 page 
     error_page 404 /index.html; 

    } 

} 

编辑:使用这样<a href="http://localhost:8080/api/auth/facebook">Login with Facebook</a>链接,但它迫使我使用的URL硬编码的,我将最终把这个应用程序域下。

新的编辑:我知道,像这样使用<a href="/api/auth/facebook">Login with Facebook</a>不起作用,因为它认为它一个角路线,因为我还没有在$ routeProvider宣布,它带我到404

回答

0

为了避免404,将target =“_ self”添加到您的链接<a href="/api/auth/facebook">Login with Facebook</a>。它将绕过角度路由器。

使用另一种方法,我认为你没有'Access-Control-Allow-Origin',因为当你使用角度$ http服务时,它被FB API的CORS同源策略阻塞。

你应该坚持链接,如果你想在角度上做到这一点,我推荐这个插件:https://github.com/sahat/satellizer

相关问题