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

我正在使用 GraphQLClient 将graphql-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 });

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


GraphQLError: Variable \"$file\" got invalid value {}; Upload value invalid

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


operations: {

    "query":"\n mutation uploadProfileImage($file: Upload!){\n uploadProfileImage(file: $file)\n }\n",  

    "variables":{"file":null}

}

map: {"1":["variables.file"]}

1: (binary)

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


jeck猫
浏览 177回答 4
4回答

慕田峪9158850

我通过在配置中将上传选项设置为 false 解决了该问题ApolloServer。new&nbsp;ApolloServer({&nbsp;schema,&nbsp;context,&nbsp;uploads:&nbsp;false&nbsp;})然后使用graphqlUploadExpress()来自 的中间件graphql-upload。app.use(graphqlUploadExpress({&nbsp;maxFileSize:&nbsp;10000,&nbsp;maxFiles:&nbsp;10&nbsp;}));希望这对遇到与我相同问题的人有所帮助😊

呼唤远方

请确保您还使用以下客户端实现apollo-upload-client:import { ApolloClient, InMemoryCache } from "@apollo/client";import { createUploadLink } from 'apollo-upload-client';const client = new ApolloClient({  cache: new InMemoryCache(),  link: createUploadLink({      uri: 'http://localhost:4000/graphql'  }),});

红颜莎娜

这取决于您使用的 ApolloClient。1-如果使用 import { ApolloClient } from 'apollo-client' 必须使用“ createUploadLink ”而不是“ createHttpLink ”意味着,import { createUploadLink } from 'apollo-upload-client'const httpLink = createUploadLink({&nbsp; uri: httpEndpoint,})2-如果使用createApolloClient,则精确这个包:import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'const { apolloClient, wsClient } = createApolloClient({&nbsp; &nbsp; ...defaultOptions,&nbsp; &nbsp; ...options,&nbsp; })``You do not need to set anything and Upload work complete.

万千封印

此外,请尝试确保csrfPrevention您的 ApolloServer 配置中未将其设置为 true&nbsp; const server = new ApolloServer({&nbsp; &nbsp; typeDefs,&nbsp; &nbsp; resolvers,&nbsp; &nbsp; csrfPrevention: false, // if this is set to true, uploads will fail&nbsp; &nbsp; uploads: false,&nbsp; &nbsp; cache: "bounded",&nbsp; &nbsp; plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })],&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript