use*_*695 10 javascript redirect node.js reactjs next.js
在我的React/nextJS应用程序中,我正在检查getInitialProps静态函数中的有效令牌.我正在使用它作为HOC - 但在这种情况下这应该不重要.
如果令牌无效(或丢失),则用户将被重定向到登录页面.这是通过redirect如下所示的功能完成的.到现在为止还挺好.
如何将用户重定向到的页面的URL传递给登录组件?
如果用户未登录并正在调用http://my-server.com/any-page之类的内容,则会将其重定向到索引页面(http://my-server.com):将会有登录名形成.如果登录成功,我想将他重定向回第一个被调用页面:http://my-server.com/any-page
我不知道如何将这些信息传递给登录功能......
与服务器,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} />
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
页/ 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
})
}
})
}
Run Code Online (Sandbox Code Playgroud)
将with-server-props.js路径替换为URL 对象
redirect(context, {
pathname: '/',
query: { redirect: req.url } // req.url should give you the current url on server side
})
Run Code Online (Sandbox Code Playgroud)
这会将重定向参数添加到网址https://example.com/?redirect=/about
然后你可以使用以下方法获取任何页面上的 url 参数getInitialProps:
this.redirectUrl = (req && req.query['redirect']) ? decodeURIComponent(req.query['redirect']) : '/'
Run Code Online (Sandbox Code Playgroud)
最后
window.location.assign(this.redirectUrl)
Run Code Online (Sandbox Code Playgroud)
希望有帮助,请告诉我。
| 归档时间: |
|
| 查看次数: |
1092 次 |
| 最近记录: |