I have my node app set like this- I've got two handlers, one for requests to the root URL and the other for the slug, and when I go to the root, it does load up, then crashes. When I go to the slug URL, same thing. This error shows up:
url is pointing to root
url has a slug
throw err; // Rethrow non-MySQL errors
What did I do wrong?
app.get(
'/:slug',
(req, res) => {
connection.query(`select * from blogs where slug="${slug}"`,
(error, results) => {
if (error) console.log(error);
console.log('url has a slug');
res.render(
'somepage',
results
)
}
)
}
)
app.get(
'/',
(req, res) => {
connection.query(`select * from blogs`,
(error, results) => {
if (error) console.log(error);
console.log('url is pointing to root');
res.render(
'index',
{
title: 'Home page',
blogs: results
}
)
}
)
}
)
One possible explanation for the error you observe:
After loading the home page with GET /, browsers make an additional GET /favicon.ico request to retrieve the icon that decorates the browser tab (which is
on StackOverflow). That additional request would be served by your "slug route", with req.params.slug = "favicon.ico". I expect the variable slug in your code to be undefined. Anyway, the select statement will probably fail during this additional request.