Cannot delete an article in crud app (mongo, express, Nodejs) - node.js

Hi I am trying to make a crud app using Node Express and mongodb. But when I am trying to delete an article from my app it says it cannot delete. I checked all the code but cant find errors. Can anyone help please?
Delete route in my code is
router.delete('/:id', async (req, res)=>{
await Article.findByIdAndDelete(req.params.id)
res.redirect('/')
})
Link to delete an article is
<form action="/articles/<%=article.id%>?_method=DELETE" method="POST" class="d-inline">
<button type="submit" class="btn btn-danger">DELETE</button>
</form>
This is my server.js file

Write your app.use(methodOverride("_method")); middleware before routing app.use('/articles', articleRouter)

Related

Passportsjs logout - document says to use app.post but fails saying "Cannot GET /logout"

The documentation for passport js https://www.passportjs.org/concepts/authentication/logout/ says..."It is a good idea to use POST or DELETE requests instead of GET requests for the logout endpoints, in order to prevent accidental or malicious logouts."
My code looks like this...
app.post('/logout', function(req, res){
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
The error I get when logging out is "Cannot GET /logout"
when I change the app.post to app.get it works no problem but that goes against what the documentation is suggesting. How do I get app.post to work?
You have to move that "logout button or link" inside your .ejs and put it inside a form, so you would be able to post that logout request.
Something like this:
<form class="" action="/logout" method="post">
<button class="" type="submit" name="button">Logout</button>
</form>
Share the code where you put the option for the user to logout and i will help with that too.

How do I get form post in Nodejs app to work on cpanel

please I have a Node.js/Express application with a form in an html file. The form works fine on my local machine when I run it,This form.html is in a public folder, below is the form attributes which also has a submit button below;
<form action="/api/students" method="post" class="was-validated shadow font-weight-bold" >...
I also have the backend api in an index.js file which is in the same directory with the public folder as below,
...
// Serving static folder
app.use(express.static(path.join(__dirname, 'public')));
// Students API Routes
app.use('/api/students', require('./routes/students'));
// Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true ,
useUnifiedTopology: true,
},
() => console.log('Connected to DB')
);
const PORT = process.env.PORT || 2100;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
I tried to deploy it on a cpanel shared hosting platform which worked somehow But the form post can not be submitted and gives request time out error. I have tried to change the form action value as below but its not working.
<form action="my_domain_name.com/api/students" method="post" class="was-validated shadow font-weight-bold" >...
<form action="my_domain_name.com:2100/api/students" method="post" class="was-validated shadow font-weight-bold" >...
Please can someone help me to solve this problem. Thanks in advance.
It sounds like the Node.js Express API can not be reached.
How are you hosting the Node app on the cpanel? It sounds like you just uploaded all the static html files to the host, but are not running the node app - hence why the request is timing out.

How can I serve mp3 file on node js?

I am building simple web app that if the user press button, it will make sound(mp3 file in the server side).
//html file
<script>
function playSound () {
document.getElementById('play').play();
}
</script>
<body>
<audio id='play', src='http://127.0.0.1:1337/', type='audio/mpeg'
<button onclick='playSound()' class='btn btn-danger btn-circle btn-lg'>
<i class='fa fa-5x fa-fire'>
</body>
//app.js
app.get('/music.mp3', function(req, res){
ms.pipe(req, res, "/music.mp3");
});
It works if I insert online source in audio attribute, but it does not serve my local server file. How can I fix this?
Thanks in advance!
To serve static files such as images, CSS files, and JavaScript files, audio, use the express.static built-in middleware function in Express.
app.use(express.static('public'));
I've already answered such type of question. See this answer

Express JS 4.x Multer Basic Upload

I'm trying to upload an image in Express JS using the Multer middleware, but running into several issues when trying to set up the absolute simplest use case.
The only error I'm receiving is: 'POST /upload 500', and my POST callback is never entered.. so I'm not even sure how to debug this case. My code is as follows:
app.js:
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: './public/photos/'}); // valid dir
app.post('/upload', upload.single('photo'), function(req, res, next){
// This callback is never reached. 500 error.
console.log(req.body);
console.log(req.files);
});
upload.ejs:
<form method='post' enctype='multipart/form-data'>
<p><input type='text', name='photo[name]', placeholder='Name'/></p>
<p><input type='file', name='photo[image]'/></p>
<p><input type='submit', value='Upload'/></p>
</form>
I can't pick out any difference between this and the current npm Multer setup documentation. More than just 'how-to' fix this, I'd really like to know why this isn't working, and what's happening under the hood that's causing it to fail.
All help welcome. THANK YOU!!!
Solved! For one, my input names were not matching:
upload.single('photo[image]').
That's what was causing the 500 error. I had a couple issues after this that were caused by using an outdated req.file packet and were easily solved by referencing the up-to-date multer documentation.

Express JS redirect to default page instead of "Cannot GET"

I am using express JS and I have a set of routes that I have defined as follows
require('./moduleA/routes')(app);
require('./moduleB/routes')(app);
and so on. If I try to access any of the routes that I have not defined in the above routes, say
http://localhost:3001/test
it says
Cannot GET /test/
But instead of this I want to redirect to my app's index page. I want this redirection to happen to all of the undefined routes. How can I achieve this?
Try to add the following route as the last route:
app.use(function(req, res) {
res.redirect('/');
});
Edit:
After a little researching I concluded that it's better to use app.get instead of app.use:
app.get('*', function(req, res) {
res.redirect('/');
});
because app.use handles all HTTP methods (GET, POST, etc.), and you probably don't want to make undefined POST requests redirect to index page.
JUst try to put one get handler with * after all your get handlers like bellow.
app.get('/', routes.getHomePage);//When `/` get the home page
app.get('/login',routes.getLoginPage); //When `/login` get the login page
app.get('*',routes.getHomePage); // when any other of these both then also homepage.
But make sure * should be after all, otherwise those will not work which are after * handler.
HTML file would be :
<form class="" action="/fail" method="post">
<button type="submit" name="button">Redirect to Homepage!</button>
</form>
Your Node.js code would be:
app.post("/fail", (req, res)=>{
res.redirect("/");
});

Resources