繁体   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