首页 > 解决方案 > 如何解决访问 DatoCMS 的 Apollo 错误 401

问题描述

我遵循了本指南:

https://medium.com/@marcmintel/quickly-develop-static-websites-with-vuejs-a-headless-cms-and-graphql-bf64e75910d6

但是当我运行时npm run dev,我的 localhost:3000 上出现错误 401

这是我的 nuxt.config.js

module.exports = {
  /*
  ** Headers of the page
  */
  head: {
    title: 'hello-world',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress bar color
  */
  loading: { color: '#3B8070' },
  /*
  ** Build configuration
  */
  build: {
    /*
    ** Run ESLint on save
    */
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  },
  modules: [
    '@nuxtjs/apollo',
  ],
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'https://graphql.datocms.com',
        getAuth: () => 'Bearer XXXXXXXXXXXXX' //my apikey
      }
    }
  }
}

这是执行查询的 vue 文件。我目前在页面中没有显示任何内容,但我仍然收到错误消息。

<template>
    <div>
        All blog posts

    </div>
</template>

<script>
import gql from 'graphql-tag'

export default {
    apollo: {
        allPosts: gql`{
            allPosts{
                title,
                text,
                slug
            }
        }`
    }
}
</script>

在 DatoCMS 中正确定义了 post 数据类型,我使用 API Explorer 对其进行了测试

标签: vuejs2apollonuxt.js

解决方案


在文章的评论中找到了解决方案。您需要将您的身份验证放在一个单独的文件中,如下所示:

~/apollo/config.js
export default function(context){
 return {
   httpEndpoint: ‘https://graphql.datocms.com',
   getAuth:() => ‘my-token’ //Bearer is added by default
 }
}        

然后在 nuxt.config.js apollo 中:

apollo: {
  clientConfigs: {
    default: ‘~/apollo/config.js’
  }
}

推荐阅读