Nuxt Server-Middleware

前陣子需要利用server middleware做fb oauth功能,於是我就在middleware資料夾新增了fbauth.js,內容:

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' }))
}
}
view raw fbauth.js hosted with ❤ by GitHub

結果build完之後,發現clientSecret竟然也一起打包進client端的js裡!!

於是我查了關於如何不將code打包進client side的資料後,就在外面包了一層 if (process.env.VUE_ENV === ‘server’) 如下:

閱讀全文 Nuxt Server-Middleware