I'm using NodeJS/Express and EJS to create a form to an API route. But I'm having a trouble connecting my post route(which contents an id) with the ejs form. How can i add the id to the ejs.
This is my post route
router.post('/:id/new', upload.single('file'), async (req, res) => { //here i'm trying to add project id to the url
//const project = await Project.findById(req.params.id)
const releasenoteData = {
user : await req.user._id,
title: req.body.title,
path: req.file.path,
originalName: req.file.originalname,
description: req.body.description,
createdAt: req.body.createdAt,
}
try {
const releasenote = await ReleaseNote.create(releasenoteData)
console.log(releasenote)
res.redirect('/')
} catch {
if (releasenoteData.path != null) {
res.redirect('/new', {
errorMessage: 'Error Creating the Release Note'
})
}
}
})
Now I want to connect the above post route with a ejs form and get the relevant data from it. How can I do that with the project id in the route.
<form action="/new" method="POST" enctype="multipart/form-data"> //here before new id should be added i think
<label for="text">Title: </label>
<input type="text" id="title" name="title">
<br><br>
<label for="file">File: </label>
<input type="file" id="file" name="file" required>
<br><br>
<label for="text">Description: </label>
<input type="text" id="description" name="description">
<br><br>
<label for="date">Upload Date: </label>
<input type="date" id="createdAt" name="createdAt">
<br><br>
<button type="submit">Add Release Note</button>
</form>
CodePudding user response:
The answer, confirmed by the OP as a working solution, is to drop the action
part of the form. This makes the form POST to its default location
As per the spec:
[...]
- Let action be the submitter element's action.
- If action is the empty string, let action be the URL of the form document.
This means that if the form is first GET, action
can be omitted and the url is preserved (actually this is handy if the url contains multiple parameters).