用axios和formdata实现图形变量上传

uubf1zoe  于 2022-12-12  发布在  iOS
关注(0)|答案(2)|浏览(179)

使用axios、graphql和formdata上传文件##

我想通过graphql和formdata用axios上传nodejs服务器中的图像,这是我的方法,但不起作用,我认为这个问题是在附加到表单数据中,但我找不到原因或在axios中获取数据

代码

let data = {
              query: `
              mutation Mutation($image: Upload!) {
                multimedia(image: $image) {
                  status
                  message
                  token
                }
              }`,
              variables: {
                image: null,
              },
            };
            let map = {
              0: ["variables.image"],
            };
            const FormD = new FormData();
            FormD.append("operation", JSON.stringify(data));
            FormD.append("map", JSON.stringify(map));
            FormD.append(0, element.file, element.file.name);
            console.log(FormD);
            await axios({
              url: "/",
              method: "POST",
              headers: {
                token: token,
                "Content-Type": "multipart/form-data",
              },
              data: FormD,
              onUploadProgress:ProgressEvent=>{
                element.loaded=ProgressEvent.loaded/ProgressEvent.total*100
              }
            })
      .then((response) => {
        if (response.data.errors) {
          const { message } = response.data.errors[0];
          toast.error(message);
        } else {
          setLoadedFiles(tempLoadedFiles);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  • 但回应是 *
    回应
{
    "message": "Request failed with status code 400",
    "name": "AxiosError",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {
            "FormData": null
        },
        "headers": {
            "Accept": "application/json",
            "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZjY3NWZiODkwNjY0N2RlZWRmMTM5ZiIsImlhdCI6MTY2MDg5NTgzMSwiZXhwIjoxNjYzNDg3ODMxfQ._5gmsMHD_HRokvoopKOit1n8YhG_sP3oR_OLRSXqZTo"
        },
        "baseURL": "http://localhost:4000/graphql",
        "url": "/",
        "method": "post",
        "data": {}
    },
    "code": "ERR_BAD_REQUEST",
    "status": 400
}

谢谢你的回答

qlckcl4x

qlckcl4x1#

我已修复此问题,不使用

let data = {
              query: `
              mutation Mutation($image: Upload!) {
                multimedia(image: $image) {
                  status
                  message
                  token
                }
              }`,
              variables: {
                image: null,
              },
            };

并在 axios 中替换它

await axios({
          url: "/",
          method: "post",
          headers: {
            "token": token,
            "Content-Type": "application/json",
          },
          data: {
            query: `
            mutation Mutation( $image : Upload!) {
              multimedia(image: $image) {
                status
                message
              }
            }`,
            variables: {
              image: element.file,
            },},
          onUploadProgress: (ProgressEvent) => {
            tempLoadedFiles[index].loaded =
              (ProgressEvent.loaded / ProgressEvent.total) * 100;
          },
        })

而且很有效。

yfwxisqw

yfwxisqw2#

该问题在节点服务器中解决
通过以下方法在服务器中修复了它:

import express from "express";
import mongoose from "mongoose";
import Router from "./routes/index.js";
import User from "./models/users.js";
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import { ApolloServer } from "apollo-server-express";
import MakeSchema from "../api/models/index.js";
import { config } from "../config/index.js";
const app = express();
const Application = () => {
  const ServerConfig = async () => {
    const server = new ApolloServer({
      schema: MakeSchema,
      playground: true,
      introspection:  "production",
      formatError(err) {
        if (!err.originalError) {
          return err;
        }
        const data = err.originalError.data;
        const code = err.originalError.code || 500;
        const message = err.message || "error";
        return { message, data, code };
      },
      context: async ({ req }) => {
        let check;
        let user;
        let userInfo;
        await User.VerifyToken(req).then((val) => {
          check = val;
        });

        if (check) {
          user = await User.findById(check.id);
          userInfo = await User.CheckUserInfo({
            fname: user.fname,
            address: user.address,
          });
        }
        if (user) {
          return { role: user.role, check, userInfo };
        }
        return { check, role: user };
      },
    });
    await server.start();
    **app.use(graphqlUploadExpress())
    app.use(express.static('public'))
    app.use('/public',express.static('public'))
    await server.applyMiddleware({ app });**
    app.listen(config.port, () => {
      console.log(`Server run on port ${config.port}`);
    });
  };

  const DatabaseConfig = () => {
    mongoose.Promise = global.Promise;
    mongoose.connect(config.database.url, config.database.options);
  };
  const Routes=()=>{
    app.use(Router)
  }

  ServerConfig();
  DatabaseConfig();
  Routes();
};
export default Application;

相关问题