使用nuxt.js在每个页面中验证HTTP标头以进行身份​​验证

时间:2020-09-08 03:59:41

标签: node.js vue.js nuxt.js server-side-rendering

我正在尝试验证向nuxt服务器发送的每个HTTP请求

在此official tutorial中, 它要求我在每个页面中添加一个validate函数,这似乎对我不起作用,因为我正在寻找一种编写一种可以验证对nuxt服务器的所有请求的中间件的方法< / strong>。

因此,我找到了nuxt的中间件支持,但是官方文档确实不友好,我一点也不了解。

我期望的是一个类似插件的模块,该模块允许我将中间件放入nuxt。 就像在Express中可以实现的一样(如下所示)。

Reading package lists... Done
Building dependency tree       
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gdb-multiarch : Depends: gdb (= 8.1-0ubuntu3.2) but it is not going to be installed
                 Depends: libpython3.6 (>= 3.6.5) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

这样我就可以轻松地根据每个对nuxt的请求验证标头。

我该如何实现?非常感谢。

2 个答案:

答案 0 :(得分:1)

我相信Nuxt Middleware是您所需要的。

middleware/auth.js

// write any custom validation functions

export default function (context) {
  context.userAgent = process.server
    ? context.req.headers['user-agent']
    : navigator.userAgent
}

然后在nuxt.config.js

// this will register the middleware functions above for every route

export default {
  router: {
    middleware: 'auth'
  }
}

答案 1 :(得分:1)

转到目录middleware/并创建一个auth.js

第一个参数是您的上下文。上下文包含许多内容,例如您的商店,应用程序,路由,重定向,还包含req

您可以检查其中包含什么上下文:https://nuxtjs.org/api/context/

export default function ({ req, res, redirect }) {
  let authenticated = false;
  if(!authenticated) {
     redirect("/login")
  }
}

您现在可以转到页面上的,并将其添加到您的export default {}

middleware: ["auth"]

现在,如果您尝试访问该页面,则应重定向到登录页面