【问题标题】:File upload in graphql apollo server from next js application using redux?使用redux从下一个js应用程序在graphql apollo服务器中上传文件?
【发布时间】:2021-10-12 09:37:12
【问题描述】:

我正在构建下一个 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;
  },
});

现在我得到了一些错误?像

【问题讨论】:

  • 那是javascript/webpack的问题。
  • 这是否回答了您的问题:fs.createReadStream is not a function?您不能在浏览器中使用fs 模块,它只能在 Node.js 环境中使用。
  • 那么,如何将formdata发送到graphql服务器?

标签: javascript webpack


【解决方案1】:

首先你使用的是next js。在前端或浏览器中不支持节点文件系统。然后正在使用graphql上传文件。 Graphql 支持多部分形式。在表单中,您只需发送文件。然后后端应用程序读取文件。所以去掉 fs.createReadStream 函数。

那么你就是运营领域。在字段中 graphql 只支持 json 格式。在您的操作字段中,json 是无效的多部分 json。所以改成这样吧。

然后将 headers 更改为 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));
}

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2019-08-20
    • 2020-02-19
    • 2019-07-23
    • 2021-03-06
    • 2013-11-09
    • 2019-09-14
    • 2020-09-11
    • 2020-10-21
    相关资源
    最近更新 更多