[英]ANGULAR: No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]No “Access-Control-Allow-Origin” header is present on the requested resource
我正在使用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>
,我會收到一個<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腳本(忽略'<'和'>'中的塊):
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>
不起作用,因為它認為它是一個Angular路線,因為我還沒有在$中聲明routeProvider,它帶我到404。
要避免使用404,請將target =“_ self”添加到您的鏈接<a href="/api/auth/facebook">Login with Facebook</a>
。 它將繞過角度路由器。
使用另一種方法,我認為你沒有'Access-Control-Allow-Origin',因為當你使用angular $ http服務時,它被FB API上的CORS同源策略阻止了。
你應該堅持鏈接,如果你想在角度端做這個,我推薦這個插件: https : //github.com/sahat/satellizer 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.