I use ejs, express, nodeJS and mySQL. This code gives me an error : Cannot POST /search .
I think the idex.ejs and the app.js is fine but I messed up the searchRouter …
app.js
const express = require('express') const app = express() app.use('/static',express.static('static')) app.set('view engine','ejs') const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()) const index = require('./router/indexRouter') const upload = require('./router/uploadRouter') const detail = require('./router/detailRouter') const edited = require('./router/editedRouter') const search = require('./router/searchRouter') app.use("/",index) app.use(upload) app.use(detail) app.use(edited) app.use(search) const port = 8080 app.listen(port, () => console.log(`Server up and running on port: ${port} !`))
searchRouter
const express = require('express') const router = express.Router() const dbCon = require('../database.js') router.get('/search',(req,res) =>{ const searched = req.body.search const query = `SELECT * FROM memes WHERE (title like "${searched} OR user like "${searched})"` dbCon.query(query, (err, results) =>{ if(err) { console.log(err) } console.log(results) res.render('detail',{memes:results}) }) }) module.exports = router
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you want to handle a POST
request to your /search
route, you’ll have to register it correctly using express.
Like this:
router.post('/search', (req, res) => {
/* ... */
});
Please note – in the code you are showing you only registered for a GET
request on said route. However (!) just from a logical standpoint, I think a GET
request for a /search
route makes more sense anyway.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0