Reputation: 165
I am trying to upload file from a react front-end with fetch
to node.js backend with multer. Below is my fetch
code:
submitpost=(e)=>{
e.preventDefault();
var data=new FormData();
data.append('file',this.state.shareImage)
fetch("http://localhost:8080/post", {
method: 'POST',
body: data
}).then((response) => {
console.log(response.json());
})
}
The image is in the state of the component. Below is the server code:
const express=require('express')
const app=express()
const bodyParser=require('body-parser')
const multer=require('multer')
const cors=require('cors')
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.json());
app.use(express.urlencoded());
app.use(cors());
var storage1 = multer.diskStorage({
destination: function (req, file, cb) {
// Uploads is the Upload_folder_name
cb(null, "images")
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now()+".jpg")
}
})
const upload = multer({
storage: storage1
})
app.post('/post',upload.single('myfile'),(req,res)=>{
console.log(req.body);
res.send(JSON.stringify({'status':'success'}))
})
app.listen(8080,function(error) {
if(error) throw error
console.log("Server created Successfully on PORT 8080")
})
When I see in the console, req.body
is empty.
This is how my input
looks like:
<input type="file"
accept="image/*"
name="myfile"
id="file"
style={{display: 'none'}}
onChange={(event)=>{this.handleChange(event)}}
/>
Below is the Request Headers as seen in network tab:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,hi;q=0.8
Connection: keep-alive
Content-Length: 135326
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryE9U4gJpcqK2hAdXC
Host: localhost:8080
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
My question is if this is the correct way to receive files. If yes, why req.body
is empty?
Please help me to find the problem.
Thank You!
Upvotes: 0
Views: 1417
Reputation: 13652
The code currently initializes the multer
middleware, but does not use it. According to the documentation, here's how you'd use it:
app.post("/post", upload.single("file"), (req, res) => {
// "file" is the name of the field which contains the file
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
console.log(req.file);
console.log(req.body);
res.send(JSON.stringify({ status: "success" }));
});
As an additional side-note, express has a helper for working with JSON. You can replace res.send(JSON.stringify(...))
with res.json(...)
:
app.post("/post", upload.single("file"), (req, res) => {
// "file" is the name of the field which contains the file
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
console.log(req.file);
console.log(req.body);
res.json({ status: "success" });
});
Upvotes: 1