【发布时间】:2021-04-02 08:33:35
【问题描述】:
应用程序在前端使用 apollo 服务器和 react。在后端我使用 apollo 服务器。该请求通过 Playground 和 Postman 工作,我没有收到任何错误。 没有 参数的前端查询也工作完美。当我在前端进行 mutation 时,我收到以下错误错误:Response not successful: Received status code 400。在后端打印调试时,我也没有得到任何参数。在 Web 控制台中:XHR POST http://localhost:4000/ 包含以下请求: {"variables":{},"query":"mutation ($title: String!, $dotColor: String!) { \n newStack(title: $title, dotColor: $dotColor) {\n stackID\n title\n dotColor\n __typename\n }\n}\n"}
src/queries/queries.js
import { gql } from "@apollo/client";
[...]
const newStackMutation = gql`
mutation($title: String!, $dotColor: String!) {
newStack(title: $title, dotColor: $dotColor) {
stackID
title
dotColor
}
}
`;
[...]
export {[...], newStackMutation};
src/components/NewStack.js
import { useMutation } from "@apollo/client";
import { newStackMutation } from "../queries/queries";
import { useState } from "react";
export default function NewStack() {
const [newStack] = useMutation(newStackMutation);
const handleNewStackSubmit = (e) => {
//newStack({variables}); actually I would pass the variables from the setState here
newStack({ title: "Test", dotColor: "red" });
};
return (
<div>
<form onSubmit={handleNewStackSubmit}>
[...]
<button type="submit" />
</div>
</form>
</div>
);
};
【问题讨论】:
-
你的类型定义中有突变类型吗?应该看起来像查询类型定义,但用于突变
-
当然,正如我所说,它适用于邮递员和操场。因此,据我所知,在后端一切都“有效”。问题一定出在前端
-
我没有看到您发布的代码 sn-ps 有任何问题,我唯一能想到的另一件事是配置有问题,例如托管 graphql 服务器的 uri 是否正确在前端
-
Client const client = new ApolloClient({ cache: new InMemoryCache(), uri: "http://localhost:4000", }); Backend const server = new ApolloServer({ cors: { origin: "http://localhost:3000", credentials: true, }, typeDefs, resolvers, playground: true, context: (ctx) => ctx, }); -
我现在知道问题出在哪里,但不知道如何解决。所以阿波罗客户端发送:
mutation ($title: String!, $dotColor: String!) {\n newStack(title: $title, dotColor: $dotColor)作为响应,这意味着阿波罗客户端不要用传递的变量替换 $ 符号。以前从未有过这样的事情