簡體   English   中英

使用redux從下一個js應用程序在graphql apollo服務器中上傳文件?

[英]File upload in graphql apollo server from next js application using redux?

我正在構建下一個 js 應用程序。 我正在嘗試將文件上傳到 graphql apollo 服務器。 這是突變-

mutation signUp($avatar: Upload!) {
  signUp(
    avatar: $avatar
    input: {
      name: "Siam Ahnaf"
      email: "siamahnaf198@yahoo.com"
      password: "siam1980"
    }
  ){
    message
    token
  }
}

在下一個 js 應用程序中,我使用 axios 發布請求。 最需要的功能-

import FormData from "form-data";
import fs from "fs";
export const signUp = (data) => async (dispatch) => {
    dispatch({ type: SIGNUP_LOADING })
    var info = new FormData();
    info.append('operations', `{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: "Siam Ahnaf", email: "siamahnaf198@yahoo.com", password: "siam1980"}){message, token}}", "variables": { "file": null } }`);
    info.append('map', '{ "0": ["variables.file"] }');
    info.append('0', fs.createReadStream(data.picture[0]));
    axios.post("http://localhost:3001/graphql", info, {
        headers: {
            ...info.getHeaders()
        }
    })
        .then(res => console.log(res))
        .catch(err => console.log(err));
}

為了使用 fs,我在 next.config.js- 中編寫了一些代碼

module.exports = optimizedImages({
  images: {
    disableStaticImages: true,
  },
  webpack5: true,
  webpack: (config) => {
    config.resolve.fallback = { fs: false };
    return config;
  },
});

現在我得到了一些錯誤? 喜歡在此處輸入圖片說明

首先,您正在使用下一個 js。 在前端或瀏覽器中不支持 node fie 系統。 然后是使用graphql上傳文件。 Graphql 支持多部分形式。 在表格中,您只需發送文件即可。 然后后端應用程序讀取文件。 所以去掉 fs.createReadStream 函數。

那么你就是運營領域。 在 graphql 字段中僅支持 json 格式。 在您的操作字段中,json 是無效的多部分 json。 所以改成這個樣子。

然后將標題更改為 Content-Type。

import FormData from "form-data";
import fs from "fs";
export const signUp = (data) => async (dispatch) => {
    dispatch({ type: SIGNUP_LOADING })
    var info = new FormData();
    info.append('operations', `{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: \\"Siam Ahnaf\\", email: \\"siamahnaf198@yahoo.com\\", password: \\"siam1980\\"}){message, token}}", "variables": { "file": null } }`);
    info.append('map', '{ "0": ["variables.file"] }');
    info.append('0', data.picture[0]);
    axios.post("http://localhost:3001/graphql", info, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(res => console.log(res))
        .catch(err => console.log(err));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM