简体   繁体   中英

Unknow field error in Gatsby GraphQL for custom query

I am usingGatsby with GraphQL. Getting unknown field error as follows:

GraphQL Error Encountered 2 error(s):
- Unknown field 'allBlogPost' on type 'Query'. Source: document `homeAymanDesktopFirstSrcPagesIndexJs2258072279` file: `GraphQL request`
  
  GraphQL request:3:3
  2 |   {
  3 |       posts: allBlogPost {
    |   ^
  4 |           nodes {
- Unknown field 'blogPost' on type 'Query'.

      file: /home/ayman/Desktop/first/src/templates/post.js

Here is my post.js template file:

import React from "react"
import { graphql } from "gatsby"

export default ({ data }) => {
    console.log(data)
    return (
        <div>
            <h1>{data.post.title}</h1>
            <div dangerouslySetInnerHTML={{ __html: data.post.html }} />
        </div>
    )
}

export const query = graphql`
    query($id: String!) {
        post: blogPost(id: { eq: $id }) {
            title
            html
        }
    }
`

My gatsby-node.js configuration can be found in this pastebin

My GraphiQL:

在此处输入图像描述


Update

After adding Asciidoc file in content/posts and content/articles , getting this error:

Cannot query field "slug" on type "BlogPost".

File: gatsby-node.js:89:16


 ERROR #11321  PLUGIN

"gatsby-node.js" threw an error while running the createPages lifecycle:

Cannot read property 'posts' of undefined



  TypeError: Cannot read property 'posts' of undefined
  
  - gatsby-node.js:99 


Your code is breaking in the gatsby-node.js , not in the template (at least for now).

Try using an async / await approach in your createPage API, something like:

exports.createPages = async ({ graphql, actions }) => {
    const { createPage } = actions
    const postTemplate = path.resolve(`./src/templates/post.js`)
 
    const postsQuery = await graphql(`
        {
            posts: allBlogPost {
                nodes {
                    id
                    slug
                }
            }
        }
    `);

  if (postsQuery.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`);

    return;
  }

        postsQuery.data.posts.nodes.forEach( node => {
            createPage({
                path: node.slug,
                component: postTemplate,
                context: {
                    id: node.id,
                },
            })
        })

It seems that you can't create your own schema properly. Ensure that your validations are correct:

if (node.internal.type === `Asciidoc`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM