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检测阵列和图像
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)
After Post Call