gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:19:54 32 4
gpt4 key购买 nike

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

尝试过的解决方案

客户端设置


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)
}
}

最佳答案

我从 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);
}
});

关于javascript - 文件上传后返回空对象 - Apollo graphql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260949/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com