Nuxt3 實作 Google 登入
Sep 17, 2022
Nuxt3 implement Google Login
前言 — 版本資訊與設定
- 使用的nuxt3版本是3.0.0-rc.4
- 這是google 登入新版API的做法(因為舊版已經不能用了,即便官網的介紹還是以舊版為主)
- 記得在oath2那個介面中,同時設定
http://localhost:3000
和http://localhost
,讓開發環境也能被授權使用google login。 - 如果是使用react或是原生html, js,則在head自行添加script
<script src=”https://accounts.google.com/gsi/client” async defer />
核心 — 主要函式
最重要的是以下兩個google api的函式,以vue來說,是寫在組件的onMounted階段。
- initialize:進行google api初始化
- renderButton:負責渲染按鈕
實作 — vue和nuxt3分別實作
重點函式:initialize和renderButton
登入按鈕的 vue組件實作(GoogleLoginButton)
nuxt實作整合應用
- nuxt.cofig.ts
- 添加env
NUXT_ENV_GOOGLE_CLIENT_ID=YOUR_GOOGLE_CLIENT_ID
實際引用GoogleLoginButton的組件(use GoogleLoginButton in other components)
⭐歡迎登入點擊拍手(按著可以點很多下喔!),這是對我最大的鼓勵呦!
⭐⭐不定期更新網頁前端的教學,或是讀書心得,歡迎訂閱我的專欄。
⭐⭐⭐本教學同步張貼在部落格:
https://www.penguin-cho.com/posts/nuxt3-google-login-button
REF
- googleAPI相關
- initialize https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.initialize
- renderButton https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.renderButton
- 舊版遷移指南https://developers.google.com/identity/gsi/web/guides/migration#popup-mode_1
- 設定API的憑證(OAuth2)https://console.cloud.google.com/apis/credentials
- 出現 the-given-origin-is-not-allowed-for-the-given-client-id-gsi 問題https://stackoverflow.com/questions/68438293/the-given-origin-is-not-allowed-for-the-given-client-id-gsi
- react實作方式(引用gapi函式庫)https://blog.logrocket.com/guide-adding-google-login-react-app/
- gapi函式庫(用這個引入函式庫可以整合其他服務的登入)https://github.com/google/google-api-javascript-client/blob/master/docs/start.md