Rails、Graphql、Apollo 客户端的验证令牌无效 [英] Invalid Auth Token with Rails, Graphql, Apollo Client

查看:36
本文介绍了Rails、Graphql、Apollo 客户端的验证令牌无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让基本的 Rails、Graphql、Apollo-Client 设置正常工作,但在 Rails 端遇到 422 错误无效身份验证令牌"的问题.

I am trying to get a basic Rails, Graphql, Apollo-Client setup working but having trouble with 422 errors 'invalid auth token' on the rails side.

我对 apollo 的使用看起来有错吗?

Does my use of apollo look wrong?

这是一个带有 graphql gem 和 apollo 客户端的 Rails 5 应用程序.

It is a Rails 5 app with graphql gem and apollo client.

const csrfToken = document.getElementsByName('csrf-token')[0].content
const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: '/graphql',
    credentials: 'same-origin',
    headers: {
      'X-CSRF-Token': csrfToken
    }
  }),
});
client.query({
query: gql`
    query Camillo2 {
      user {
        id
        email
        created_at
      }
    }
  `,
})
.then(data => console.log(data))
.catch(error => console.error(error));  

Rails 日志:

Started POST "/graphql" for ::1 at 2017-03-10 08:51:58 -0800
Processing by GraphqlController#create as */*
Parameters: {"query"=>"query Camillo2 {\n  user {\n    id\n    email\n    created_at\n    __typename\n  }\n}\n", "operationName"=>"Camillo2", "graphql"=>{"query"=>"query Camillo2 {\n  user {\n    id\n    email\n    created_at\n    __typename\n  }\n}\n", "operationName"=>"Camillo2"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)

推荐答案

自 Apollo 2.0 和根据

Since Apollo 2.0 and according to

https://github.com/apollographql/apollo-client/blob/master/Upgrade.md

就这么办

const csrfToken = document.querySelector('meta[name=csrf-token]').getAttribute('content');
const client = new ApolloClient({
    link: new HttpLink({
        credentials: 'same-origin',
        headers: {
            'X-CSRF-Token': csrfToken
        }
    }),
    cache: new InMemoryCache()
});

这篇关于Rails、Graphql、Apollo 客户端的验证令牌无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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