我正在尝试从我的react应用访问graphql服务器,这是我的代码
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { ApolloProvider } from 'react-apollo';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient, gql } from 'apollo-boost';
const httpLink = createHttpLink({
uri: 'http://someserver/graphql',
});
const cache = new InMemoryCache();
const client = new ApolloClient({
link: httpLink,
cache,
request: (operation) => {
const token = process.env.REACT_APP_AUTH_TOKEN;
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : '',
},
});
},
});
client
.query({
query: gql`
{
getAllUser {
users {
id
data {
name
address
}
}
}
}
`,
})
.then((res) => console.log(res));
ReactDOM.render(
<ApolloProvider client={client}>
<React.StrictMode>
<App />
</React.StrictMode>
</ApolloProvider>,
document.getElementById('root')
);
但是每当我在浏览器上加载我的应用程序时,我都会得到这个
网络错误:响应失败:接收到状态码401
我认为授权存在问题,但是我该如何解决?
您还可以访问服务器代码/日志吗?没有这些很难说清楚,但是许多graphql API会返回更详细的错误消息。我建议您查看正文是否包含任何提示。一些应用程序不使用承载令牌,而是使用会话cookie等,因此希望错误的实际内容可以为您提供帮助!