graphql - 如何使用 Nuxt ServerMiddleware 和 Apollo GraphQL 处理 301 重定向

标签 graphql apollo http-status-code-301 nuxt.js vue-apollo

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

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

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

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

this recommendation之后我在 ~/serverMiddleware/redirect.js 文件中创建了以下代码

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 文件中,如下所示:

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

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

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

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

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

最佳答案

最后我在nuxtjs's github中找到了解决方案

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

完成!

关于graphql - 如何使用 Nuxt ServerMiddleware 和 Apollo GraphQL 处理 301 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326878/

相关文章:

jestjs - 当我尝试使用 NestJS、Jest 和 GraphQLFederationModule 进行测试时出错

asp.net - 在asp.net中更推荐的301重定向方式是什么?

ruby - Mailgun::CommunicationError 通过 nginx '301 Moved Permanently' 错误

reactjs - 如何为 graphql 生成 TypeScript 定义

graphql - 如何在 Gatsby 中对 GraphQL 查询进行单元测试

swift - 将来自 Cognito 的用户信息与 AWS Amplify GraphQL 相关联

typescript - 无论如何在 typescript 中做嵌套的 Pick<> 类型

javascript - 将自定义类型列表传递给 GraphQL 突变

internet-explorer - 在 Internet Explorer 11 中重定向到 PDF 会导致多个请求

reactjs - GraphQL 返回数据但在代码中未定义