[英]Returning empty object after file upload - Apollo graphql
將文件上傳到服務器后返回一個空的 object。我已經嘗試了 inte.net 上的所有解決方案。 但仍然沒有發現我的代碼有什么問題。
嘗試解決方案
客戶端設置
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 客戶端而不是 apollo-boost,如本期所述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);
}
});
當我使用nestjs
( apollo-server-express
) 和graphql-upload
時出現同樣的問題。
通過刪除uploads: false
從 GraphQL 選項修復(可能使用apollo-server-express
內置上傳方法),並將這些行添加到package.json
:
"resolutions": {
"fs-capacitor": "^6.x.x",
"graphql-upload": "^13.0.0"
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.