本地运行的Create React App / Apollo Client尝试访问GraphQL API时出现400错误。
创始人
2024-11-30 08:30:24
0

当使用本地运行的Create React App与Apollo Client尝试访问GraphQL API时出现400错误,可能有几种解决方法。

  1. 检查GraphQL API的URL:首先确保Apollo Client的createHttpLinkApolloProvider中的uri选项设置正确。确保URL正确,并且不包含任何拼写错误或额外的斜杠。
import { createHttpLink } from '@apollo/client';

const httpLink = createHttpLink({
  uri: 'https://example.com/graphql', // 确保URL正确
});
  1. 检查请求头:GraphQL API可能需要特定的请求头,如授权令牌或身份验证。确保在Apollo Client的createHttpLinkApolloProvider中设置了正确的请求头。
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')
);
  1. 检查GraphQL查询:确保发送的GraphQL查询语句正确,并与API的模式匹配。检查查询语句中的字段名称、参数和变量是否正确。
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}

{/* ... */}
); }
  1. 检查GraphQL API的错误响应:如果GraphQL API返回400错误,它可能包含有关出现问题的详细信息。在Apollo Client的错误处理中,您可以打印出错误消息以了解问题所在。
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错误。

相关内容

热门资讯

WePoKe辅助挂!德扑ai代... WePoKe辅助挂!德扑ai代打[透视]其实真的有挂(有挂神器)-哔哩哔哩1、德扑aiai辅助优化,...
AApoker透明挂!德州辅助... AApoker透明挂!德州辅助神器wpk[透视]其实真的有挂(有挂软件)-哔哩哔哩,您好,AApok...
wepoke透明挂!poker... wepoke透明挂!pokerwoeld安卓下载[透视]其实真的有挂(有挂APP)-哔哩哔哩,亲,有...
wpk辅助透视!德州辅助软件线... wpk辅助透视!德州辅助软件线上[辅助挂]原来真的有挂(有挂软件)-哔哩哔哩是一款可以让一直输的玩家...
WPK透明挂!aapoker透... 您好,aapoker这款游戏可以开挂的,确实是有挂的,需要了解加微【439369440】很多玩家在这...
WPK透明挂!wepoke软件... WPK透明挂!wepoke软件透明挂视频[辅助挂]原来真的有挂(有挂神器)-哔哩哔哩1、超多福利:超...
wepoke透明挂!手机德州a... wepoke透明挂!手机德州app辅助[透视]原来真的有挂(有挂AI)-哔哩哔哩1、打开德州poke...
aapoker透明挂!德扑ai... 自定义德扑ai系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是想分...
AApoker透明挂!德州ai... AApoker透明挂!德州ai辅助神器wpk[辅助挂]原来真的有挂(有挂AI)-哔哩哔哩1、德州ai...
wpk ai辅助!cloud辅... 自定义系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是想分享给你好...