在我的 React/nextJS 应用程序中,我正在检查 getInitialProps
静态函数中的有效 token 。
我将其用作 HOC - 但在这种情况下这无关紧要。
如果 token 无效(或丢失),用户将被重定向到登录页面。这是由 redirect
函数完成的,如下所示。到目前为止,一切顺利。
如何将用户从其重定向到登录组件的页面的 url 传递?
如果用户没有登录并且正在调用类似 http://my-server.com/any-page 的东西,他被重定向到索引页面( http://my-server.com ):会有一个登录表单。如果登录成功,我想将他重定向回第一个调用页面: http://my-server.com/any-page
- 以未登录用户的身份调用受限页面
- 重定向到索引登录页面
- 登录后重定向回1的页面。
我不知道如何将此信息传递给登录功能...
with-server-props.js
export default WrappedComponent =>
class extends Component {
static async getInitialProps (context) {
const { req, pathname } = context
let isValid = false
if (req && req.headers) {
const cookies = req.headers.cookie
if (typeof cookies === 'string') {
const cookiesJSON = jsHttpCookie.parse(cookies)
initProps.token = cookiesJSON['auth-token']
if (cookiesJSON['auth-token']) {
jwt.verify(cookiesJSON['auth-token'], secret, (error, decoded) => {
if (error) {
console.error(error)
} else {
isValid = true
}
})
}
}
}
// Redirect to index (=login) page if isValid is false
if (!isValid && pathname && pathname !== '/') {
redirect(context, pathname ? '/?ref=' + pathname : '/')
}
return initProps
}
render () {
return <WrappedComponent {...this.props} />
}
}
redirect.js
import Router from 'next/router'
export default (context, target) => {
if (context.res) {
// server
context.res.writeHead(303, { Location: target })
context.res.end()
} else {
// In the browser, we just pretend like this never even happened ;)
Router.replace(target)
}
}
pages/index.js
在 index.js 上有 submit
功能来登录用户。在那里,用户应该被重定向到初始页面:
_onSubmit (event) {
this.props.loginMutation({
variables: { username, password }
}).then(response => {
const token = response.data.token
if (token) {
Cookies.set('auth-token', token, { expires: 1 })
this.props.client.resetStore().then(() => {
window.location.assign('/') // <-- Redirect to initial called page
})
}
})
}
最佳答案
在您的 with-server-props.js
中将路径替换为 URL object
redirect(context, {
pathname: '/',
query: { redirect: req.url } // req.url should give you the current url on server side
})
这会将重定向参数添加到 url https://example.com/?redirect=/about
然后您可以使用 getInitialProps
获取任何页面上的 url 参数:
this.redirectUrl = (req && req.query['redirect']) ? decodeURIComponent(req.query['redirect']) : '/'
终于
window.location.assign(this.redirectUrl)
希望有帮助,告诉我。
关于javascript - JS : How to pass url through redirect function to login function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355703/