【问题标题】:Can't set Authentication header for Apollo client无法为 Apollo 客户端设置身份验证标头
【发布时间】:2018-10-17 01:49:17
【问题描述】:

我正在开发一个 Laravel 应用程序,该应用程序在客户端使用 React 和 Redux,并带有 React 预设和 Mix。我决定为 API 尝试 GraphQL,而不是通常的 REST API 方法,到目前为止它运行良好。但是,我现在卡住了。

我使用 Apollo 作为我的 HTTP 客户端,因为它是为使用 GraphQL 而构建的。过去我使用JWT Auth 来保护API,所以我自然也采用了这种方法,因为实现只是添加适当标头的一个例子。我关注了the instruction on setting headers with Apollo,但标题没有设置。这是有问题的 JS 文件:

import LinkList from './components/LinkList';
import React from 'react';
import ReactDOM from 'react-dom';
import {Container} from './container';
import {createStore} from 'redux';
import reducer from './reducer';
import {Provider} from 'react-redux';
import {fromJS} from 'immutable';
import ApolloClient from 'apollo-boost';
import gql from 'graphql-tag';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
    uri: window.initialData.graphql_route
});

const authLink = setContext((_, { headers }) => {
    const token = window.initialData.jwt;
    // return the headers to the context so httpLink can read them
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : "",
        }
    }
});

const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
});

client.query({
    query: gql`{
        links {
            id
            title
            link
        }}`
}).then(result => console.log(result));

const store = createStore(
    reducer,
    fromJS(window.initialData),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

if (document.getElementById('list')) {
    ReactDOM.render(
        <Provider store={store}>
            <Container />
        </Provider>,
        document.getElementById('list')
    );
}

我在视图中填充window.initialData,其中包含必要的数据,包括作为window.initialData.jwt 的JWT 令牌。在authLink 的定义中设置断点没有任何作用,意味着它永远不会被调用。

知道出了什么问题吗?我已经非常密切地遵循文档中的示例,所以我能想到的只是它们可能已经过时了。

【问题讨论】:

    标签: jwt graphql apollo


    【解决方案1】:

    Info: Don't save your token in the localStorage Is it safe to store a JWT in localStorage with ReactJS?

    您正在使用“apollo-boost”中的 ApolloClient,但您的令牌配置是用于另一个 ApolloClient,即“apollo-client”中的 { ApolloClient }。

    如果您想使用来自 apollo-boost 的 ApolloClient 保存令牌:

    const client = new ApolloClient({
      uri: ...,
      request: async operation => {
        const token = localStorage.getItem('token');
        operation.setContext({
          headers: {
            authorization: token ? `Bearer ${token}` : ''
          }
        });
       }
    });
    

    Apollo Boost migration

    【讨论】:

    • localStorage.getItem('token') 是同步的,因此不应等待
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2015-11-30
    • 2022-10-22
    • 1970-01-01
    相关资源
    最近更新 更多