如何通过express.js将Cookie值传递给所有路由?

时间:2019-01-05 10:07:56

标签: javascript express cookies next.js

我正在尝试使用Express.js作为服务器的Next.js。我想通过检查是否存在用户的身份验证cookie(在登录时在客户端上设置了cookie)来对服务器上的用户进行身份验证。

这是我的操作方式(我正在自定义下一个默认的server.js文件):

const express = require( 'express' )
const next = require( 'next' )

const cookiesMiddleware = require( 'universal-cookie-express' )
const dev = process.env.NODE_ENV !== 'production'
const app = next( { dev } )
const handle = app.getRequestHandler()

app.prepare().then( async () => {

    const server = express()

    server.use( cookiesMiddleware() )

    server.get( '/news', ( req, res ) => {
        const actualPage = '/news'
        const userID = req.universalCookies.get( 'userID' )
        const queryParams = { userID: userID }
        app.render( req, res, actualPage, queryParams )
    })  

    server.get( '*', ( req, res ) => {
        return handle( req, res )
    }) 

    server.listen( 3000, ( err ) => {
        if( err ) throw err
        console.log( '> Ready on http://localhost:3000' )
    })

})

因此,基本上,我使用universal-cookie-express包作为中间件从请求中读取userID cookie,并将其作为参数传递给/news路由,该路由具有拥有特殊的server.get,因为它必须按照Next.js的说明以自己的页面呈现。

然后在新闻页面中,我在getInitialProps中获得cookie值:

static async getInitialProps( { query } ) {
    const { userID } = query
    return { userID }
}

render() {
    return <p>The user ID is { this.props.userID }</p>
}

这非常好。

顺便说一下,上面的代码有效。问题是我有几种不同的路由,并且不想读取每个server.get函数中的cookie。因此,我的问题是,如何读取userID cookie并将其传递给所有路由,以及如何在每个页面中访问它?

2 个答案:

答案 0 :(得分:0)

我发现自己是一个非常简洁的解决方案。在设置路线之前,我刚刚添加了以下内容:

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( { req } ) {
    console.log( 'User ID is', req.userID ) 
}

答案 1 :(得分:-1)

有几种方法可以做到这一点:

  1. 使用反应状态管理(redux / fluxible)

    Read more about redux

    Read more about fluxible

  2. 使用react-cookies依赖项

import { Component } from 'react'
import cookie from 'react-cookies'

class MyApp extends Component {
  constructor () {
    super()
    this.onLogin = this.onLogin.bind(this)
    this.onLogout = this.onLogout.bind(this)
  }

  componentWillMount() {
    // Get the userID value from react-cookie
    this.state =  { userId: cookie.load('userId') }
  }

  onLogin(userId) {
    this.setState({ userId })
    // Store the cookie in react-cookie
    cookie.save('userId', userId, { path: '/' })
  }

  onLogout() {
    // Destroy the cookie from react-cookie
    cookie.remove('userId', { path: '/' })
  }

  render() {
    const { userId } = this.state
    return (
      <div />
    );
  }
}

  1. 使用窗口sessionStorage

    Sessionstorage为每个给定的来源维护一个单独的存储区域,该存储区域在页面会话期间有效(只要浏览器处于打开状态,包括页面重新加载和还原)。浏览器关闭并重新打开后,会话将自动销毁。

    // Store the cookie
    sessionStorage.setItem("userId", userId);
    // Get the value of cookie
    sessionStorage.getItem("userId");