1

我希望能更清楚地了解我可能出错的地方。对不起,如果我问了很多问题,因为我感到有点失落并且在这个问题上被困了大约一周。

目前,我已经更改了用于与 apollo-client 链接的包。以前的包是apollo-link-http现在我正在使用apollo-absinthe-upload-link,因为我读过它允许图像上传。

如下所示

const httpLink = createLink({
    uri: 'http://localhost:4000/api',
    credentials: 'same-origin',
    fetch,
    fetchOptions
});

将信息发送到后端没有任何变化,但在上传图像方面我确实继续迷失方向。此图像的目的是上传到云端,然后将 url 信息与产品详细信息一起保存。

我正在使用一个钩子const [ images, setImages ] = useState([]);和一个输入<input type="file" placeholder="Upload Image" onChange={handleUploadImage} />

onChange 函数的目的是将图像信息设置为 images 属性。当我们将突变发送到后端时,它的完成方式如下

const buildForm = () => {
    let storeID = 2;
    const fileData = fileList.fileList.map((file) => {
        return file.originFileObj;
    });
    const data = new FormData();
    data.append('fileData', images);
    debugger;
    return {
        productName,
        productDescription,
        productPrice,
        productType,
        isReturnable,
        storeID,
        fileData: data
    };
};

当它运行时,在我的控制台中我得到一个错误,Uncaught (in promise) Error: GraphQL error: Argument "fileData" has invalid value $fileData.我在后端看到键fileData有一个空对象作为它的值。我希望就可能出现的问题或我应该考虑的问题获得一些建议。如果有人提到 CURL,请解释一下,因为我不知道这对于 GraphQL 和发送突变意味着什么。感谢您对此事的帮助。

PS - 正在使用的突变调用是

export const CREATE_PRODUCT_MUTATION = gql`
    mutation CreateProduct(
        $storeID: Int!
        $productName: String!
        $productDescription: String!
        $productPrice: Decimal!
        $productType: Int!
        $isReturnable: Boolean!
        $fileData: Upload!
    ) {
        createProduct(
            product: {
                productName: $productName
                productDescription: $productDescription
                productPrice: $productPrice
                productType: $productType
                isReturnable: $isReturnable
            }
            storeId: $storeID
            fileData: $fileData
        ) {
            id
            productName
            productDescription
            productPrice
        }
    }
`;

更新 - 网络退货请求

{"errors":[{"locations":[{"column":0,"line":2}],"message":"Argument \"fileData\" has invalid value $fileData."}]}

后端架构

@desc "List a new product"
field :create_product, :product do
  arg(:product, :new_product)
  arg(:store_id, :integer)
  arg(:file_data, non_null(:upload))
4

1 回答 1

1

apollo-absinthe-upload-link需要一个FileBlob类型的变量(请参见此处),但您传递fileData的是 type FormData

由于您的input类型是file,您可以这样做:

const handleUploadImage = (event) => setImages(event.target.files);

const buildForm = () => ({
  productName,
  productDescription,
  productPrice,
  productType,
  isReturnable,
  storeID: 2,
  fileData: images[0],
});

参考:

文件选择器

反应滴区

于 2020-02-07T05:29:33.670 回答