当使用本地运行的Create React App与Apollo Client尝试访问GraphQL API时出现400错误,可能有几种解决方法。
createHttpLink
或ApolloProvider
中的uri
选项设置正确。确保URL正确,并且不包含任何拼写错误或额外的斜杠。import { createHttpLink } from '@apollo/client';
const httpLink = createHttpLink({
uri: 'https://example.com/graphql', // 确保URL正确
});
createHttpLink
或ApolloProvider
中设置了正确的请求头。import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
link: createHttpLink({
uri: 'https://example.com/graphql',
headers: {
Authorization: 'Bearer YOUR_TOKEN', // 添加正确的请求头
},
}),
cache: new InMemoryCache(),
});
ReactDOM.render(
,
document.getElementById('root')
);
import { useQuery, gql } from '@apollo/client';
const GET_DATA = gql`
query GetData($id: ID!) {
getData(id: $id) {
// 检查查询的字段是否正确
id
name
// ...
}
}
`;
function MyComponent() {
const { loading, error, data } = useQuery(GET_DATA, {
variables: { id: '123' }, // 确保传递正确的变量
});
if (loading) return Loading...
;
if (error) return Error :(
;
return (
{/* 使用返回的数据 */}
{data.getData.name}
{/* ... */}
);
}
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
// ...
onError: (error) => {
console.log('GraphQL error:', error.message); // 打印错误消息
},
});
ReactDOM.render(
,
document.getElementById('root')
);
通过检查上述因素,您应该能够解决Create React App与Apollo Client尝试访问GraphQL API时出现的400错误。