使用 axios 向 graphql 发出请求

时间:2021-05-25 06:44:40

标签: node.js reactjs axios graphql

尝试从 RESTAPI 折射到 GraphQL,我相信我的设置基本正确,但我收到 must provide query string 作为错误消息。我在 GET 中没有看到任何请求。

我正在使用 axios、express、node、react,我不知道是否有一些简单的包可以使用,因为我能找到的所有教程都是关于 Apollo

我对 axios 的请求

export const fetchRecipes = () => {
  axios({
    url: `${URL}/recipes/beer`,
    method: "get",
    data: {
      query: `
     query beerRecipeList{
        recipe{
     title
     name
     createdAt
     selectedFile
     method
     style
     targetABV
     rating
     votes
    }
   }
   `,
    },
  })
    .then((res) => {
      console.log("fetch working");
      console.log(res);
    })
    .catch((err) => {
      console.log(err.message);
    });
};

和我的 graphql 后端

import { graphqlHTTP } from "express-graphql";
import { buildSchema } from "graphql";
import recipeSheet from "../../models/beer/recipeSheet.js";

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type recipe {
    title: String
    name: String
    createdAt: String
    selectedFile: String
    method: String
    style: String
    targetABV: Int
    rating: Int
    votes: [String]

  }
 
  type Query {
    beerRecipeList: [recipe]
  }
`);

const resolvers = {
  Query: {
    beerRecipeList: async () => {
      try {
        console.log("resolver firing");
        const recipes = await recipeSheet.find();
        return recipes;
      } catch (error) {
        throw error;
      }
    },
  },
};

const graphql = graphqlHTTP({
  schema,
  resolvers,
  graphiql: true,
});

export default graphql;

1 个答案:

答案 0 :(得分:0)

通过 REST API 使用 Graphql 查询进行 API 调用时。它总是一个邮政电话。将 axios 方法从 get 更改为 post