我搜索了很长时间,但我找不到答案。
当有人从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不工作....
我是否必须为每个fetch 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' })
})