我正在嘗試使用 Apollo-boost-upload 設定 graphQl 檔案上傳的前端。後端程式碼基於此鏈接 https://dev.to/dnature/handling-file-uploads-with-apollo-server-2-0-14n7。 在 server.js 檔案中新增以下行後,現在已到達解析器斷點
const { apolloUploadExpress } = require("apollo-upload-server"); app.use(apolloUploadExpress({ maxFileSize: 1000000000, maxFiles: 10 }));
修改上傳類型的架構後
scalar Upload
這是 Vue 元件
<input type="file" style="display:none" ref="fileInput" accept="image/*" @change="upload" >
//Upload method upload({ target: { files = [] } }) { if (!files.length) { return; } this.logoImage = files[0]; }, //Dispatching action from vue component this.$store.dispatch("uploadLogo", { image: this.logoImage }); //Vuex action const uploadLogo = async (context, payload) => { context.commit("setLoading", true); try { const { data } = await apolloClient.mutate({ mutation: UPLOAD_LOGO, variables: {file: payload.image}, context: { hasUpload: true, }, }); context.commit("setLoading", false); console.log("Logo:", data.uploadLogo); } catch (error) { context.commit("setLoading", false); console.log(error); } }; //Mutation export const UPLOAD_LOGO = gql` mutation uploadLogo($file: Upload!) { uploadLogo(file: $file) { _id path filename mimetype user { _id } } } `; // Apolloclient config on main.js import ApolloClient from "apollo-boost-upload"; import { InMemoryCache } from "apollo-boost"; import VueApollo from "vue-apollo"; // Set up Apollo Client export const defaultClient = new ApolloClient({ uri: "http://localhost:4000/graphql", cache: new InMemoryCache({ addTypename: false, }), fetchOptions: { credentials: "include", }, request: (operation) => { // if no token in local storage, add it if (!localStorage.someToken) { localStorage.setItem("someToken", ""); } // operation adds the token to authorizatrion header, which is sent o backend operation.setContext({ headers: { authorization: "Bearer " + localStorage.getItem("someToken"), }, }); }, onError: ({ graphQLErrors, networkError }) => { if (networkError) { console.log("[networkError]", networkError); } if (graphQLErrors) { for (const error of graphQLErrors) { console.dir(error); if (error.name === "AuthenticationError") { // set auth errir in state store.commit("setError", error); // signout user to clear error store.dispatch("signUserOut"); } } } }, });
這是後端更新的 typedef(舊程式碼已註解掉),如果這有助於識別問題
const logoUploadTypeDefs = gql` type File { _id: ID! path: String! filename: String! mimetype: String! encoding: String! user: User } # input Upload { # name: String! # type: String! # size: Int! # path: String! # } scalar Upload type Mutation { uploadLogo(file: Upload!): File } type Query { info: String logo: File! } `;
現在,Node 應用程式崩潰並顯示以下日誌
我必須將“apollo-upload-server”更改為“graphql-upload”
更改 1:
#註解掉「apollo-upload-server」並使用「graphql-upload」
在中間件中,使用了這個
更改 2:
#取代舊程式碼
另外,在解析器中,我加入了這個
更改3:
#從解析器檔案中的 graphql-upload 匯入 Upload
#請參閱 Apollo 文件以了解更多詳細資訊。這修復了節點崩潰並出現錯誤“_openReadFs 超出最大調用堆疊大小...”的問題