[英]from fetch api in react to express res.redirect
I searched for a long time, but I could not find the answer. 我搜索了很长时间,但找不到答案。
When someone requests data from an api, fetch or ajax ( in SPA react ) 当有人从api,fetch或ajax请求数据时(在SPA中反应)
I want to send data to only the logged in or authenticated user, 我只想将数据发送给已登录或已验证的用户,
if not logged user or not authenticated user, 如果不是登录用户或未认证用户,
I would like to redirect to 'someReAuthPage' 我想重定向到“ someReAuthPage”
My strategy is as follows. 我的策略如下。
in SPA react client 在SPA反应客户端
fetch('/api/someData', {
method : "GET",
})
.then(......)
in express server 在快递服务器中
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')
}
but this code not working res.redirect not working.... 但是此代码不起作用res.redirect不起作用....
Do I have to write a redirect conditional statement for every fetch api? 我是否必须为每个提取api编写重定向条件语句?
Is there a way to redirect directly from the server without using conditional statement in client fetch api??? 有没有一种方法可以直接从服务器重定向,而无需在客户端获取api中使用条件语句?
somebody help me ... 来人帮帮我 ...
Write a middleware function. 编写中间件函数。 Here's my implementation for checking if the user is logged in in an ecosystem where I use Firebase.
这是用于检查用户是否在使用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");
});
}
And to use it with a particular route: 并将其用于特定路线:
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.