简体   繁体   English

将带有值的变量发送到所有路由 node.js 的前端

[英]send a variable with a value to front end of all routes node.js

I have req.session values that are being stored upon login.我有登录时存储的req.session值。 But what I want to do is access them on every page of my app (front-end(ejs)), but i don't want to go into every single route/function i have and pass it.但是我想要做的是在我的应用程序的每个页面(前端(ejs))上访问它们,但我不想 go 进入我拥有的每一个路由/功能并传递它。 So i was wondering if there is a universal way to pass req.session to the front-end from one route and access them on all pages?所以我想知道是否有一种通用的方法可以将req.session从一条路由传递到前端并在所有页面上访问它们?

my routes look like this:我的路线如下所示:

app.get('/', (req, res) => {
   res.render("index.ejs");
})

sorry if this is an odd question, but wondering if there is universal ways to do things like this.抱歉,如果这是一个奇怪的问题,但想知道是否有通用的方法来做这样的事情。

In authentication, you probably need these two things:在身份验证中,您可能需要以下两件事:

  • Front end: Context to form a global state around authentication information前端:上下文围绕认证信息形成全局state
  • Back end: Retrieve user info based on session id sent & Middleware to authenticate the requests后端:根据发送的 session id 和中间件检索用户信息以验证请求

You should set up something like authContext to fetch information of sessionID from backend, and trigger some function on login and logout to revise the authentication.您应该设置类似authContext以从后端获取 sessionID 的信息,并在登录和注销时触发一些 function 以修改身份验证。 You may want to research React Context to figure out how to apply "global state", if you are not familiar with that.如果您不熟悉,您可能想研究 React Context 以弄清楚如何应用“全局状态”。

In the backend, use middleware to authenticate every HTTP request and apply that middleware to the route you want to apply authentication.在后端,使用中间件对每个 HTTP 请求进行身份验证,并将该中间件应用于要应用身份验证的路由。

Which can go something like this:哪个可以 go 是这样的:

async function auth (req, res, next) {
  try {
    const session = await MySessions.findById(req.sessionID);
    if (!session) throw 'Not authenticated'
    else next()
  } catch (error) {
    // Response will be rejected, and wont be passed to route due to not sending next()
    return res.status(401).send({ error })
  }
}

// Example of applying middleware auth to route you need.
router.delete('/:postId', auth, async (req, res) => { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM