Javascript 如何使用express.js将cookie值传递给所有路由?
我正在试用Next.js,它使用Express.js作为服务器。我想通过检查用户的身份验证cookie是否存在来验证服务器上的用户(cookie是在登录时在客户端上设置的) 下面是我的做法(我正在自定义下一个默认的server.js文件): 因此,基本上我使用Javascript 如何使用express.js将cookie值传递给所有路由?,javascript,express,cookies,next.js,Javascript,Express,Cookies,Next.js,我正在试用Next.js,它使用Express.js作为服务器。我想通过检查用户的身份验证cookie是否存在来验证服务器上的用户(cookie是在登录时在客户端上设置的) 下面是我的做法(我正在自定义下一个默认的server.js文件): 因此,基本上我使用universalcookieexpress包作为中间件从请求中读取userIDcookie,并将其作为参数传递给/news路由,该路由有自己的特殊服务器 然后在新闻页面中,我在getInitialProps中获得cookie值: stat
universalcookieexpress
包作为中间件从请求中读取userID
cookie,并将其作为参数传递给/news
路由,该路由有自己的特殊服务器
然后在新闻页面中,我在getInitialProps
中获得cookie值:
static async getInitialProps( { query } ) {
const { userID } = query
return { userID }
}
render() {
return <p>The user ID is { this.props.userID }</p>
}
static async getInitialProps( { req } ) {
console.log( 'User ID is', req.userID )
}
静态异步getInitialProps({query}){
const{userID}=query
返回{userID}
}
render(){
return用户ID为{this.props.userID}
}
非常好
顺便说一下,上面的代码是有效的。问题是我有几个不同的路由,不想在每个服务器中读取cookie。get
函数。所以我的问题是,如何读取userID
cookie并将其传递给所有路由,以及如何在每个页面中访问它 有几种方法可以实现这一点:
使用反应状态管理(redux/fluxible)
使用react cookies
依赖项
从'react'导入{Component}
从“react cookies”导入cookie
类MyApp扩展组件{
构造函数(){
超级()
this.onLogin=this.onLogin.bind(this)
this.onLogout=this.onLogout.bind(this)
}
组件willmount(){
//从react cookie获取用户ID值
this.state={userId:cookie.load('userId')}
}
onLogin(用户ID){
this.setState({userId})
//将cookie存储在react cookie中
save('userId',userId,{path:'/'})
}
onLogout(){
//从cookie中销毁cookie
删除('userId',{path:'/'})
}
render(){
const{userId}=this.state
返回(
);
}
}
我找到了一个非常简洁的解决方案。在设置路线之前,我刚刚添加了以下内容:
server.use( ( req, res, next ) => {
req.userID = req.universalCookies.get( 'userID' )
req.userToken = req.universalCookies.get( 'userToken' )
next()
})
这通过将cookie附加到req
对象,使cookie可用于每个路由。因此,在服务器上,您可以按如下方式访问它:
server.get( '/news', ( req, res ) => {
console.log( 'User ID is', req.userID )
})
在客户端上,如果您像我一样使用Next,您可以在getInitialProps
中访问它:
static async getInitialProps( { query } ) {
const { userID } = query
return { userID }
}
render() {
return <p>The user ID is { this.props.userID }</p>
}
static async getInitialProps( { req } ) {
console.log( 'User ID is', req.userID )
}
谢谢,但我在服务器文件中寻找一些可以工作的东西,因为我觉得这只是一种更干净的方式。我从来没有真正使用过Express,但我读过一些方法,比如Express.all()
,我认为这些方法可以满足我的需要,但我自己似乎无法解决。。。