使用Vue-Apollo调用GraphQL接口时持续返回Bad Request错误
Vue-apollo调用GraphQL API返回Bad Request问题排查
以下是几个直接导致Bad Request的问题及修复方案:
1. 变量名完全不匹配
你的GraphQL查询定义了接收$ownerZipcode变量,但实际传入的是parcelId,后端无法识别参数,直接返回Bad Request。
修正后的调用代码变量部分:
variables: { ownerZipcode: "7657574gg" // 和查询定义的变量名一致 }
2. no-cors模式导致请求不合法
你在HttpLink中设置了mode: 'no-cors',这个模式会强制浏览器屏蔽所有自定义请求头(包括GraphQL必需的Content-Type: application/json),后端无法解析请求体,必然返回错误。
修正后的客户端配置:
link: new HttpLink({ uri: 'http://localhost:8080/graphql', fetchOptions: { mode: 'cors', // 或者直接删除这个配置,默认就是cors } }),
同时要确保后端服务配置了CORS,允许前端所在域名的跨域请求。
3. 检查GraphQL查询的字段与后端定义是否一致
- 确认后端的查询类型名称是
Parcel(注意大小写,GraphQL对字段/类型名大小写敏感) - 确认参数名
Owner_Zipcode和后端Schema中定义的参数名完全一致 - 可以先用GraphQL Playground或Postman直接发送该查询,验证查询本身是否有效
修正后的完整调用代码示例:
const result = ref(null); async function query() { const apolloClient = createApolloClient(); try { const queryResult = await apolloClient.query({ query: gql` query Parcel($ownerZipcode: String) { Parcel(Owner_Zipcode: $ownerZipcode) { PIN Owner_Name Owner_Zipcode } } `, variables: { ownerZipcode: "7657574gg" } }); console.log('queryResult is ', JSON.stringify(queryResult)); result.value = queryResult.data; } catch(error) { console.error(error); } }
内容的提问来源于stack exchange,提问作者Molamin Ceesay
相关产品推荐
相关产品推荐

