I’m trying to post something, but always get error.
articlesRouter.post('articles/:target', async (req, res) => {
const target = req.params.target.replaceAll("_", " ")
const article = await Article.findOne({where: {title: target}})
if (article)
{
const author = req.body.commentAuthor
const text = req.body.commentText
await article.createComment({author, text})
console.log("POST METHOD IS WORKING")
}
})
Form:
<form method="post">
<textarea placeholder="Title of your article" id="title" name="articleTitle"></textarea>
<br />
<textarea placeholder="Body of your article" id="body" type="text" name="articleBody"></textarea>
<br />
<button id="submit" type="submit">Done</button>
</form>
GET method
articlesRouter.get('/articles/:target', async (req, res) => {
const target = req.params.target.replaceAll("_", " ")
const searchResult = await Article.findOne({where: {title: target}})
if (searchResult)
{
const correspondingComments = await searchResult.getComments()
res.render('../views/currentArticle', {title: searchResult.title, text: searchResult.body, comments: correspondingComments})
}
else{
console.log('Error')
}
})
How you can see, path to article consists of /articles
and /title_of_article
. I think that problem at this line articlesRouter.post('articles/:target'.....
May be I can’t use post method with /:params???
Thanks for reading!
2
Answers
To fix this, you need to make sure that the names of the form fields match the keys you are accessing in the server-side code. Here’s how you can update your form to match the expected keys:
need a ‘/’ before articles for a complete route path.
Form:
app.js:
test.js: