变量“$file”得到无效值{};上传值无效

Jes*_*mes 3 javascript file-upload node.js graphql antd

我正在使用 GraphQLClient fromgraphql-request向我的服务器发送请求。我正在尝试通过执行以下操作来上传文件:

const graphQLClient = new GraphQLClient('http://localhost:4000/graphql', {
    credentials: 'include',
    mode: 'cors',
});
const source = gql`
    mutation uploadImage($file: Upload!) {
        uploadImage(file: $file)
    }
`;
const file: RcFile = SOME_FILE; // RcFile (from antd) extends File
await graphQLClient.request<{uploadImage: boolean}>(source, { file });
Run Code Online (Sandbox Code Playgroud)

但是,当我以这种方式向服务器发送请求时,出现以下错误:

GraphQLError: Variable \"$file\" got invalid value {}; Upload value invalid
Run Code Online (Sandbox Code Playgroud)

这是我的请求在控制台中的样子:

operations: {
    "query":"\n mutation uploadProfileImage($file: Upload!){\n uploadProfileImage(file: $file)\n }\n",  
    "variables":{"file":null}
}
map: {"1":["variables.file"]}
1: (binary)
Run Code Online (Sandbox Code Playgroud)

其他人遇到过这个问题吗?我似乎无法将文件上传到我的后端。

Jes*_*mes 9

我通过在ApolloServer配置中将上传选项设置为 false 来解决这个问题。

new ApolloServer({ schema, context, uploads: false })
Run Code Online (Sandbox Code Playgroud)

然后使用graphqlUploadExpress()从中间件graphql-upload

app.use(graphqlUploadExpress({ maxFileSize: 10000, maxFiles: 10 }));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助遇到与我相同问题的任何人

  • 我正在尝试同样的事情,但收到错误:“POST body 丢失。您忘记使用 body-parser 中间件了吗?”。你遇到过吗? (2认同)