2017-02-16 71 views
0

我對我正在設計的簡單應用程序的體系結構有懷疑。谷歌Oauth實施使用MEAN堆棧

我休息基於API服務器是在節點是在http://localhost:3000 我的客戶是在http://localhost:4200

寫在角2在開發我的休息節點API服務器我成功實施,我使用http://localhost:3000/auth/google測試護照谷歌認證和 我得到重定向到谷歌登錄頁面,然後進一步登錄後,我重定向到我的/配置文件服務的我的其餘節點api

現在我想做的一樣,但起點是我的角度客戶端調用節點api服務器調用google auth。所以我最初的請求從 http://localhost:4200,它做一個http.get到 http://localhost:3000/auth/google。希望谷歌的身份驗證頁面顯示爲我進行認證,但我得到下面的錯誤

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_ur …=1000090953925-p7jof0qa284ihknb5sor3i4iatnqarvo.apps.googleusercontent.com. Redirect from ' https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_ur …=1000090953925-p7jof0qa284ihknb5sor3i4iatnqarvo.apps.googleusercontent.com' to ' https://accounts.google.com/ServiceLogin?passive=1209600&continue=https://a …sercontent.com%26from_login%3D1%26as%3D60339aeceb428c&oauth=1&sarp=1&scc=1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我已經提供的網址與無論是在谷歌身份驗證頁面的端口授權的JavaScript源 http://localhost:3000 http://localhost:4200 和下授權的重新導向的URI 我已經包括 http://localhost:3000/auth/google/callback

下面在節點API服務器代碼

app.get('/ AUT h/google',passport.authenticate('google',{scope:['profile','email']})); app.get( '/ AUTH /谷歌/回調', passport.authenticate( '谷歌',{ successRedirect: '/簡檔', failureRedirect: '/用戶' }), );

任何幫助表示讚賞

回答

0

兩件事情:因爲後端和前端是你需要讓你的後端不同的端口包括你的反應的CORS header 'Access-Control-Allow-Origin'。像這樣的東西,如果你正在使用快遞:

res.header('Access-Control-Allow-Origin', '*'); 

而且,只要確保在瀏覽器的地址是不斷HTTP://本地主機,而不是文件://本地主機

+0

嗨Roy,我不希望api服務器能夠被任何其他應用程序調用,除了前端,所以我有下面的api服務器,只允許我的客戶端應用程序運行在port4200上res.header('Access- Control-Allow-Origin','http:// localhost:4200'); ('Access-Control-Allow-Methods','GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers','Content-Type'); –

+0

嘿Vinay,如果你指定一個域名,你也應該添加協議。因此,在localhost:4200前添加http://。 –

+0

不工作,然後我添加了*但仍然與重定向問題XMLHttpRequest無法加載http:// localhost:3000/auth /谷歌。從'http:// localhost:3000/auth/google'重定向到'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_ur...=1000090953925-p7jof0qa284ihknb5sor3i4iatnqarvo.apps.googleusercontent.com'已被CORS策略阻止:請求需要預檢,這是不允許跟蹤跨源重定向的。 –

0

所有你需要做的就是 發送$window.location.href="URL"

希望它可以幫助