我正在使用MEAN Stack编写Web应用程序,无论我尝试或搜索,我都遇到了无法解决的问题。
我正在尝试使用ExpressJS使用passport / passport-facebook登录。如果我在浏览器的URL中写localhost/api/auth/facebook
,一切运行正常。
但是,如果我在我的HTML代码中创建一个元素,例如<a href="/api/auth/facebook">Login with Facebook</a>
,则会将我带到404 page
(请参阅下面的nginx)。
如果我尝试使用Angular方式,例如<button ng-click="login_fb()">Login with Facebook</button>
,我会收到No 'Access-Control-Allow-Origin' header is present on the requested resource.
错误。
我相信我应该使用<a href="...">
元素,但我认为我的nginx脚本会阻止它,因为我在我的NodeJS服务器上启用了CORS,其中包含:
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脚本(忽略'&lt;'和'&gt;'中的块):
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>
这样的链接,但它强制我使用硬编码的网址,我最终将此应用程序放在域名下。
新编辑:我意识到像<a href="/api/auth/facebook">Login with Facebook</a>
一样使用它是行不通的,因为它认为它是一个Angular路由,而且因为我没有在$ routeProvider中声明,所以它需要404.
答案 0 :(得分:0)
要避免使用404,请添加target =&#34; _self&#34;到您的链接<a href="/api/auth/facebook">Login with Facebook</a>
。它将绕过角度路由器。
使用另一种方法,我认为你得到No&#39; Access-Control-Allow-Origin&#39;因为当您使用角度$ http服务时,它会被FB API上的CORS同源策略阻止。
你应该坚持使用链接,如果你想在角度端做这个,我推荐这个插件:https://github.com/sahat/satellizer。