我正在使用 Next.js 开发一个网站的前端,它通过 graphql 从 Wordpress 站点中提取数据,更准确地说是在 WPGraphQL 插件的帮助下。在本地一切正常,包括构建应用程序;但是,当我尝试使用 Vercel CLI 中的 vercel
命令(或通过推送到 Git)将其部署到 Vercel 时,一旦向 graphql 服务器发出请求,构建就会由于以下错误而失败:< /p>
<块引用>
GraphQL 请求必须至少包含这两个参数之一: “查询”或“查询 ID”
基本上,对服务器的调用有效,但就像未传递查询文档一样。但是,相同的代码在本地运行良好!
这是我用来包装所有 graphql 请求的辅助函数:
export const graphqlRequest = async ( key, query, queryVars, authToken = null ) => {
try {
const backendUrl = process.env.NEXT_PUBLIC_GRAPHQL_URL
const res = await fetch( `${backendUrl}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...( authToken ? { "Authorization": `Bearer ${authToken}` } : {} )
},
body: JSON.stringify({
query: query, // The query here seems not to be seen when deploying to Vercel...
variables: queryVars
})
})
const resData = await res.json()
if( ! res.ok ) throw new WpApiErr( resData )
const { data, errors: err } = resData || {}
if( err && ! data ) {
throw new WPGraphQLErr( err ) // This is when the error is thrown!
}
return {
data: data || null,
err: err || null,
}
} catch( err ) {
throw( err )
}
}
然后我像这样使用它:
export const fetchPostsStaticPaths = async () => {
const query = `
{
posts( first: 10 ) {
nodes {
slug
mainCat
}
}
}
`
const { data } = await graphqlRequest( "/posts-paths", query ) || {}
// Do something with data
}
我尝试直接在 graphqlRequest
中对查询文档进行硬编码,但这没有帮助...