'Why image not getting sent with post request?
I have a form that upon submission should send the user input as post request.
The code for the form is:
<form class="news-container" enctype="multipart/form-data">
<h1>Post Your News</h1>
<br/>
<br/>
<input type="text" name="title" class="title" placeholder="Title"/>
<br/>
<br/>
<input type="textbox" name="content" class="content" placeholder="Content"/>
<br/>
<br/>
<input type="file" name="thumbnail" class="thumbnail"></input>
<br/>
<br/>
<select class="category" name="category">
<option value="Political" name="Political">Political</option>
<option value="Technical" name="'Technical">Technical</option>
<option value="Entertainment" name="Entertainment">Entertainment</option>
<option value="Sports" name="Sports">Sports</option>
</select>
<br/>
<br/>
<input type="checkbox" name="featured"><span>Featured Content</span></input>
<br/>
<br/>
<input type="submit" class="submit-btn"></input>
</form>
The submit-handler for the form is:
submitbtn.addEventListener('click', (e) => {
e.preventDefault();
var flag=validateForm();
console.log(flag)
if(flag)
{
const data=new FormData(form);
console.log(data)
postData(data);
}
})
async function postData(data) {
await fetch('http://localhost:5000/create', {
method: 'POST',
body: data
})
}
Since I am sending files also with the form input I am using multipart/form-data as the encoding type. The code for server file which has the multer for image-upload is:
const express=require('express');
const app= express();
const router=express.Router();
const multer=require('multer');
const storage=multer.memoryStorage();
const uploads=multer({storage});
// const News=require('./news/news');
app.use('/', router)
app.use(express.static('./public')); //keep in mind while serving a directory , it will by default serve the index.html file in that directory.
router.post('/create',uploads.single('thumbnail'),(req,res)=>{
console.log(req.body);
res.send("Successful");
})
app.listen(5000,()=>{
console.log("Server listening on 5000 port");
})
However the image is not getting sent with the post request.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
