English 中文(简体)
React Axios multipart/formdata Array not working
原标题:React Axios multipart/form-data Array not Working

我正试图通过含有图像的轴线发送数据集,因此我必须使用多部分/格式的数据。 当我试图发送一个阵列数据时,结果只是一个空阵。 我正在使用Axios版本1.6.5,它应当具有自动序列化。 我不知道我所缺的是什么。 这是我的准则。 j)

import AxiosInstance from "../Axios";
.....
AxiosInstance.post(`manager/`, {
  title: data.title,
  url: data.url,
  date: date,
  category: data.category,
  level: ["easy", "medium"], //to make sure I send array 
  scope: data.scope,
  image: data.image,
  description: data.description,
}).then((res) => {
    console.log(res);
});

这是我的结果:

data: 
  category: false
  created: "2024-01-27T17:58:38.028124Z"
  date: "2024-01-31"
  description: "Testing only"
  id: 17
  image: "http://127.0.0.1:8000/images/manager/Testing.jpg"
  level: []
  scope: true
  slug: "test"
  title: "test"
  updated: "2024-01-27T17:58:38.028124Z"
  url: "https://test.com

I tried to send the data from Postman to make sure it was not my backend problem and I worked fine. This is what I tried in Postman enter image description here

How to implement this in the Axios? What am I missing?

我确实赞赏你的帮助,事先感谢你!

问题回答

You can use FormData() It supportarray data like level: ["easy", "medium", "hard"] in React Component

Snippet Code

const [levels, setLevels] = useState(["easy", "medium", "hard"]);
const formData = new FormData();
levels.forEach(level => formData.append( level[] , level));

const response = await axios.post( http://localhost:3001/manager , formData, {
   headers: {
       Content-Type :  multipart/form-data 
   }
});

Demo

#1 node.js Server using express library

Specially multer library support form-data Save as server.js

const express = require( express );
const cors = require( cors );
const multer = require( multer );

const app = express();
const upload = multer();
app.use(express.json());

// Middlewares
app.use(cors()); // For cross-origin resource sharing

app.post( /manager , upload.none(), (req, res) => {
    const levels = req.body.level;
    const image = req.body.image;
    // Other passing data add in here
    // ex) title = req.body.title;

    console.log( Received levels: , levels);
    console.log( Received image: , image);

    // Handle your array data and image as needed here
    // ...

    // Sending back a JSON response
    res.json({ levels: levels, image: image });
});


// Server listening
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Install server Dependencies

npm install express cors multer

Run Server

node server.js

POST Call Testing by Postman

检查URL检测阵列和图像

“enterography


FormComponent in React

import React, { useState } from  react ;
import axios from  axios ;

const FormComponent = () => {
    const [levels, setLevels] = useState(["easy", "medium", "hard"]);
    const [image, setImage] = useState("http://127.0.0.1:8000/images/manager/Testing.jpg");

    const [responseMessage, setResponseMessage] = useState(  );

    const handleSubmit = async (event) => {
        event.preventDefault();

        const formData = new FormData();
        levels.forEach(level => formData.append( level[] , level));
        
        formData.append( image , image);
        // Other passing data add in here
        // ex) formData.append( title ,  Data Title );

        try {
            const response = await axios.post( http://localhost:3001/manager , formData, {
                headers: {
                     Content-Type :  multipart/form-data 
                }
            });
            console.log(response.data);
            setResponseMessage(JSON.stringify(response.data, null, 2)); // Formatting JSON for display
        } catch (error) {
            console.error( There was an error! , error);
            setResponseMessage( Error: Could not get a response. );
        }
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <button type="submit">Submit Levels</button>
            </form>
            {responseMessage && <p>Server Response: {responseMessage}</p>}
        </div>
    );
};

export default FormComponent;

Before Post Call (or Before button click)

“entergraph

After Post Call

“entergraph





相关问题
WordPress Data Storage Efficiency

I ve been asked to review a WordPress plugin of sorts and try to find ways of making it faster. The premise of this plugin is basically to store a bunch of users and shifts and appointments and ...

Convert a 2D array index into a 1D index

I have two arrays for a chess variant I am coding in java...I have a console version so far which represents the board as a 1D array (size is 32) but I am working on making a GUI for it and I want it ...

Convert an array of integers for use in a SQL "IN" clause

Surely there is a framework method that given an array of integers, strings etc converts them into a list that can be used in a SQL "IN" clause? e.g. int[] values = {1,2,3}; would go to "(1,2,3)"

Sorting twodimensional Array in AS3

So, i have a two-dimensional Array of ID s and vote count - voteArray[i][0] = ID, voteArray[i][1] = vote count I want the top 3 voted items to be displayed in different colors, so i have a 2nd Array -...

C++ Array Sort Me

Stuck on an array sorter. Have to sort numbers from largest to smallest. I m trying two loops (one nested in the other). Here s the code: int counter=0; // inner counter int counter2=0; // outer ...

PHP array callback functions for cleaning output

I have an array of output from a database. I am wondering what the cleanest way to filter the values is example array Array ( [0] => Array ( [title] => title 1 ...

Best practice of big javascript objects

sry for this imprecise topic name. I am querying a dataset a lot of times so using ajax request would end up in tons of http requests. For this reason I decided to use the json encode method to ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

热门标签