[英]from fetch api in react to express res.redirect
我搜索了很長時間,但找不到答案。
當有人從api,fetch或ajax請求數據時(在SPA中反應)
我只想將數據發送給已登錄或已驗證的用戶,
如果不是登錄用戶或未認證用戶,
我想重定向到“ someReAuthPage”
我的策略如下。
在SPA反應客戶端
fetch('/api/someData', {
method : "GET",
})
.then(......)
在快遞服務器中
app.get('/api/:blah', (req, res, next) => {
if(logged in or authenticated user){
next()
} else {
res.redirect('someReAuthPage')
}
})
app.get('/api/someData', (req, res) => {
..........
res.json('someJsonData')
}
但是此代碼不起作用res.redirect不起作用....
我是否必須為每個提取api編寫重定向條件語句?
有沒有一種方法可以直接從服務器重定向,而無需在客戶端獲取api中使用條件語句?
來人幫幫我 ...
編寫中間件函數。 這是用於檢查用戶是否在使用Firebase的生態系統中登錄的實現。
// Verify the user identity
const verifyoAuth = (req, res, next) => {
const idToken = req.token || ''; // I get the token using BearerToken parser.
if( idToken == '' ){
return returnQueryError(res, 401, "Unauthorized");
}
fbAdmin.auth().verifyIdToken(idToken).then( user => {
req.user = user;
next(); // resume to next route.
}).catch( error => {
// Report the incident
eventsLogger.error( error );
// Send back 401 for usr
returnQueryError(res, 401, "Unauthorized");
});
}
並將其用於特定路線:
app.get('/api/:blah', verifyoAuth, (req, res, next) => {
const { user } = req; // the `user` object would have some data about the authenticated user.
// Return what data
res.json({ msg: 'I am authenticated' })
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.