如何使用 Nuxt ServerMiddleware 和 Apollo GraphQL 处理 301 重定向 [英] How to process 301 redirects with Nuxt ServerMiddleware and Apollo GraphQL

查看:172
本文介绍了如何使用 Nuxt ServerMiddleware 和 Apollo GraphQL 处理 301 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个 Vue/Nuxt 应用,并结合修改后的 Saleor 安装来在线销售产品.

I am currently building a Vue / Nuxt app coupled with a modified Saleor installation to sell products online.

当我们从现有系统迁移时,我们需要能够处理从旧网站网址到新网站网址的 301 重定向.

As we are migrating from an existing system we need to be able to process 301 redirects from our old website's URLs into the new websites URLs.

我已修改 API 以响应以下 GraphQL 查询.

I have modified the API to respond to the following GraphQL query.

export const CHECK_REDIRECTS_QUERY = gql`
  query Redirect($oldPath: String) {
    redirect(oldPath: $oldPath) {
      oldPath
      newPath
    }
  }
`

此建议之后,我创建了以下代码位于 ~/serverMiddleware/redirect.js 文件中

Following on from this recommendation I have created the following code in a ~/serverMiddleware/redirect.js file

import { CHECK_REDIRECTS_QUERY } from '~/graphql/navigation/queries'

export default function(req, res, next) {
  console.log('redirects middleware')
  // context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
  this.$apollo
    .query({
      query: CHECK_REDIRECTS_QUERY,
      variables: {
        oldPath: '/test/11/old/'
      }
    })
    .then(({ data }) => {
      if (data.redirect.newUrl !== '') {
        res.writeHead(301, { Location: data.redirect.newUrl })
        res.end()
      }
    })
}

我也将其添加到我的 nuxt.config.js 文件中,如下所示:

I have also added this to my nuxt.config.js file as follows:

 ... 
 serverMiddleware: ['~/serverMiddleware/redirect.js'],
 ...

这不起作用,但我不仅没有得到重定向,我希望函数开头的 console.log 也不会触发.

This does not work but not only do I not get the redirect I would expect the console.log at the beginning of the function also does not fire.

此外,我还尝试使用 github 推荐中编写的代码,这非常不稳定",在大约 50 次服务器重启中可能会触发两次.

Additionally, I have also tried using the code as it was written in the github recommendation and this is very "flakey" firing probably twice in about 50 server restarts.

我没有收到任何关于 apollo 无法在服务器中间件中使用的控制台通知,并且该站点的其余部分似乎运行正常.

I'm not picking up any console notifications that apollo cannot be used within the servermiddleware and the rest of the site seems to function correctly.

另外,为了澄清起见,我假设中间件应该在每个页面上自动触发,而不需要从组件手动调用?

Also, - for clarification - I assume the middleware should just fire automatically on every page and does not need to be called manually from a component?

推荐答案

终于在nuxtjs 的 github

res.writeHead(301, { Location: redirect.to })
res.end()

完成!

这篇关于如何使用 Nuxt ServerMiddleware 和 Apollo GraphQL 处理 301 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆