前陣子需要利用server middleware做fb oauth功能,於是我就在middleware資料夾新增了fbauth.js,內容:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default async function (req, res, next) { | |
var querystring = require('querystring') | |
var axios = require('axios') | |
var query = querystring.parse(req._parsedOriginalUrl.query) | |
var appId = query.appId | |
var redirectUri = query.redirectUri.replace('#_=_', '') | |
var code = query.code | |
if (!appId || !redirectUri || !code) { | |
// response fail | |
res.writeHead(404, { 'Content-Type': 'application/json' }) | |
res.end(JSON.stringify({ msg: 'Login Failed' })) | |
return false | |
} | |
try { | |
// get access token | |
var clientSecret = process.env.FB_APP_SECRET | |
var url = `https://graph.facebook.com/v6.0/oauth/access_token?client_id=${appId}&redirect_uri=${redirectUri}&client_secret=${clientSecret}&code=${code}` | |
var result = await axios.get(url) | |
var token = result.data.access_token | |
// get userid | |
var useridUrl = `https://graph.facebook.com/me?&access_token=${token}` | |
var uinfo = await axios.get(useridUrl) | |
var uid = uinfo.data.id | |
// response success | |
res.writeHead(200, { 'Content-Type': 'application/json' }) | |
res.end(JSON.stringify({ token: token, uid: uid })) | |
} catch (e) { | |
// response fail | |
res.writeHead(404, { 'Content-Type': 'application/json' }) | |
res.end(JSON.stringify({ msg: 'Auth Failed' })) | |
} | |
} |
結果build完之後,發現clientSecret竟然也一起打包進client端的js裡!!
於是我查了關於如何不將code打包進client side的資料後,就在外面包了一層 if (process.env.VUE_ENV === ‘server’) 如下:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default async function (req, res, next) { | |
if (process.env.VUE_ENV === 'server') { | |
oauth的code... | |
} | |
} |
問題就解決了!但總覺得不是很合理,明明叫server-middleware但卻會被build進client-side用的js。
直到最近重翻doc才發現,當初secret key會被打包進去的原因是,因為當初我覺得反正都是middleware,就一起放middleware資料夾。但當我將server middleware分別放入新建的server-middleware資料夾後,發現原本發生的問題都不存在了…恩…總之就是我沒仔細看文件啦…orz
因此可以推定,middleware資料夾內的所有檔案,跟mixin資料夾內的所有檔案一樣,都會被打包進app.xxxx.js內,而不是有需要的時候才load。雖然這樣看起來是很合理,但隨著網站越長越大,很多共用的東西要拉出來的時候,就會累積越來越多非頁面關鍵需求的東西,這點似乎有點麻煩…