GraphQL - 查询看起来不错,但出现 400 错误

发布于 2025-01-10 17:47:23 字数 2054 浏览 0 评论 0原文

因此,每当我尝试通过突变将产品添加到库存列表时,我都会收到 POST http://localhost:3000/graphql 400(错误请求)。我可以毫无问题地在沙箱中执行突变。而且,检索信息的查询工作得很好。我仔细检查了所有使用的名称,似乎没有任何问题。下面是代码:

来自 App.jsx:

async createProduct(product) {
    const query = `mutation addProduct($product: ProductInputs!) {
      addProduct(product: $product) {
        id
      }
    }`;

    await fetch('/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, variables: { product }})
    });

    await this.loadData();
}

来自 schema.graphql:

enum InventoryCategory {
  Shirts
  Jeans
  Jackets
  Sweaters
  Accessories
}

type Product {
  id: Int!
  category: InventoryCategory!
  name: String!
  price: Float
  imageURL: String
}

"Toned down Product, used as inputs, without server generated values."
input ProductInputs {
  category: InventoryCategory!
  name: String
  price: Float
  imageURL: String
}

##### Top level declarations

type Query {
  productList: [Product!]!
}

type Mutation {
  addProduct(product: ProductInputs!): Product!
}

来自 server.js

const inventoryDB = [];

const resolvers = {
  Query: {
    productList,
  },
  Mutation: {
    addProduct,
  },
};

function productList() {
  return inventoryDB;
}

function addProduct(_, { product }) {
  product.id = inventoryDB.length + 1;
  inventoryDB.push(product);
  return product;
}

有什么明显不正确的地方吗?我似乎无法弄清楚为什么我总是收到 400 错误。我似乎找不到查询(突变)本身的问题。有什么想法吗?

编辑:检索信息的查询工作得很好。请参阅下面的代码:

async loadData() {
    const query = `query {
      productList {
        id
        category
        name
        price
        imageURL
      }
    }`;

    const response = await fetch('/graphql', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ query })
    });

    const body = await response.text();
    const result = JSON.parse(body);
    this.setState({ products: result.data.productList });
}

So, whenever I try to add a product to the inventory list, via a mutation, I get a POST http://localhost:3000/graphql 400 (Bad Request). I can perform the mutation in the sandbox without issue. And, the query to retrieve information works just fine. I have double-checked all the names being used and nothing seems off. Here is the code:

From App.jsx:

async createProduct(product) {
    const query = `mutation addProduct($product: ProductInputs!) {
      addProduct(product: $product) {
        id
      }
    }`;

    await fetch('/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, variables: { product }})
    });

    await this.loadData();
}

From schema.graphql:

enum InventoryCategory {
  Shirts
  Jeans
  Jackets
  Sweaters
  Accessories
}

type Product {
  id: Int!
  category: InventoryCategory!
  name: String!
  price: Float
  imageURL: String
}

"Toned down Product, used as inputs, without server generated values."
input ProductInputs {
  category: InventoryCategory!
  name: String
  price: Float
  imageURL: String
}

##### Top level declarations

type Query {
  productList: [Product!]!
}

type Mutation {
  addProduct(product: ProductInputs!): Product!
}

From server.js

const inventoryDB = [];

const resolvers = {
  Query: {
    productList,
  },
  Mutation: {
    addProduct,
  },
};

function productList() {
  return inventoryDB;
}

function addProduct(_, { product }) {
  product.id = inventoryDB.length + 1;
  inventoryDB.push(product);
  return product;
}

Is there anything that stands out as being obviously incorrect? I cannot seem to figure out why I keep getting the 400 error. I cannot seem to find an issue with the query (mutation) itself. Any thoughts?

Edit: The query to retrieve information works just fine. See below for the code:

async loadData() {
    const query = `query {
      productList {
        id
        category
        name
        price
        imageURL
      }
    }`;

    const response = await fetch('/graphql', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ query })
    });

    const body = await response.text();
    const result = JSON.parse(body);
    this.setState({ products: result.data.productList });
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡紫姑娘! 2025-01-17 17:47:23

所以,我找到了问题所在。问题在于价格,GraphQL 期望该价格是一个浮点数,但我发送的是一个字符串。我必须将文本输入转换为正确的格式,瞧,它成功了。对于转换,我使用:

parseFloat(form.price.value.substring(1))

并还使用:

{new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(product.price)}

以确保正确的显示格式。

So, I figured out the problem. The issue was with the price, which GraphQL expected to be a float, but I was sending a string. I had to convert the text input to the proper format and voila, it worked. For the conversion I used:

parseFloat(form.price.value.substring(1))

and also used:

{new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(product.price)}

to ensure correct display formatting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文