文件上传后返回空对象-Apollo graphql

时间:2019-12-10 05:45:22

标签: javascript graphql react-apollo apollo-client apollo-server

将文件上传到服务器后,返回一个空对象。我已经尝试了互联网上的所有解决方案。但仍然没有发现我的代码出了什么问题。

尝试过的解决方案

客户端设置


const httpLink = createUploadLink({
  uri: 'http://localhost:5000/graphql',
})

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem('token')
  return {
    headers: {
      ...headers,
      authorization: token
    }
  }
})

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
  onError: ({ networkError, graphQLErrors }) => {
    console.log("graphQLErrors", graphQLErrors);
    console.log("networkError", networkError);
  },
})

客户突变

  const [createAd, { loading }] = useMutation(gql`
    mutation createAd($file: Upload!) {
      createAd(file: $file) {
        message
      }
    }
  `, {
    onCompleted(data) {
      console.log(data)
    }, onError(data) {
      console.log(data)
    }
  })


  const handleUploadFile = ({
    target: {
      validity,
      files: [file]
    }
  }) => {
    if (validity.valid) {
      console.log(file)
      createAd({ variables: { file } }).then(() => {
        apolloClient.resetStore()
      })
    }}



 <input type="file" required onChange={handleUploadFile} />

服务器graphql模式

type Mutation {
  createAd(file: Upload!): Return!
}

type Return {
  data: String,
  message: String,
  error: String
}

服务器突变

  async createAd(_, {file}, { request }) {
    try {
      console.log('-- runs --')
      console.log(file) // returning empty object
      const photo = await file
      console.log(photo) // still returning empty object, whats wrong?

      return {
        message: 'uploadeding',
        data: `tesst ${JSON.stringify(photo)}`
      }
    } catch (err) {
      console.log(err)
    }
  }

1 个答案:

答案 0 :(得分:1)

我正在从apollo-boost导入Apollo客户端以设置createUploadLink,我需要从apollo-client而非apollo-boost导入apollo客户端,如本期https://github.com/jaydenseric/apollo-upload-client/issues/114

所述

我将设置更改为

import ApolloClient from "apollo-client"; // here where I did the mistake 
import { ApolloProvider } from "@apollo/react-hooks";
import { InMemoryCache } from "apollo-cache-inmemory";
import { setContext } from "apollo-link-context";
import { createUploadLink } from "apollo-upload-client";

const link = createUploadLink({
  uri: "http://localhost:5000/graphql"
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("token");
  return {
    headers: {
      ...headers,
      authorization: token
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(link),
  cache: new InMemoryCache(),
  onError: ({ networkError, graphQLErrors }) => {
    console.log("graphQLErrors", graphQLErrors);
    console.log("networkError", networkError);
  }
});