I'm using ionic angular in frontend and I' trying to send a formdata that contains a file and also 2 strings. Apparently its being sent however I don't know how to read that information on the server side
FRONTEND
private fil3: File;
changePicture(fileChangeEvent){//this functions is called by an input file
this.fil3 = fileChangeEvent.target.files[0];
let a1 = "a1"
let a2 = "a2"
let b1 = "b1"
let b2 = "b2"
let formData = new FormData();
formData.append('photo', this.fil3, this.fil3.name);
formData.append(a1, a2);
formData.append(b1, b2);
fetch('http://localhost:3000/up', {
method: 'POST',
body: formData,
headers:{
/* 'Content-Type': 'application/json' */
'Content-Type': "multipart/form-data"
},
mode: "cors",
}).then(res =>{ res.json().then((data)=>{
console.log("filename: " data.filename);
console.log("originalname: " data.originalname);
console.log("message: " data.message);
this.avatar="../../assets/uploads/" data.filename
})
})
.catch(error => {console.error('Error:', error)})
.then(response => {console.log(response)});
}//changePicture
SERVER
function updatePicture (req, res) {
console.log("req.body: " req.body)
}
On the server side I'm just trying to read each element of the formdata individually so I can work with them. These elements are the file and two other strings(a1,a2,b1,b2). This console.log on the server prints this req.body: [object Object]
I tried things like
console.log("req.body: " req.body.a1)
console.log("req.body: " req.body.[1])
but certainly do not work, I get undefined
, I have no idea how to handle this, any word of advice?
MINIMUN REPRODUCIBLE CODE OF BACKEND
const express = require ('express')
const bodyParser = require ('body-parser')
const app = express()
const api = express.Router()
const cors = require('cors')
app.use(bodyParser.urlencoded({ extended:false}))
app.use(bodyParser.json())
app.use(cors({
origin: true
}));
const PORT = 3000;
app.listen(config.port, ()=>{
console.log(`Server running on port: ${PORT}`)
})
api.post('/up', (req, res) =>{
console.log(req.body)
})
CodePudding user response:
Firstly, remove this part :
headers:{
/* 'Content-Type': 'application/json' */
'Content-Type': "multipart/form-data"
}
because if you define Content-Type
manually, you can't inform about boundary
information. It need to managed automatically by browser because you send files too.
Secondly, you need a library to parse you're multi-part data. You can use formidable
:
const formidable = require('formidable');
//You're other codes
app.post('/up', (req, res) => {
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
console.log('fields: ', fields);
console.log('files: ', files);
res.send({ success: true });
});
});
For my side this log something like :
fields: { a1: 'a2', b1: 'b2' }
files: {
file: PersistentFile {
...