Alright, so I am trying to serve a ejs file to be rendered. This file is inside a different directory, so when I try to write that path it still doesn't work. Here is the problematic code:
app.get('/views2/personal-form', (req, res) => {
res.render('/views2/personal-form');
});
My ejs page is inside the folder views2 inside of the folder views. So as an example all of these following routes minus the one listed above are served:
app.get('/back-home', (req, res) => {
res.render('back-home');
});
app.get('/business', (req, res) => {
res.render('business')
});
app.get('/account', (req, res) => {
res.render('account');
})
app.get('/personal-form', (req, res) => {
res.render('personal-form')
});
I have tried putting the line of code with personal-form in it in numerous places and to no avail. Any recommendations/suggestions would be greatly appreciated. In the picture, you can see the two 'views' folders. I just want to be able to serve view files from multiple view directories so I can organize my app better.
Ok never-mind I just got it.
app.get('/personal-form', (req, res) => { res.render('views2/personal-form') });
Related
I'm a bit confused about the Express priority order for all the routes.
This is what I've done following some stackoverflow answers and other guides on internet.
I have some http requests and this is the order: is it right in your opinion? If not, why? Thanks!
app.get('/', (req, res) => {
...
});
app.get('/:car', (req, res) => {
...
});
app.get('/:car/:eng', (req, res) => {
...
});
app.put('/:car/:feature_id', (req, res) => {
...
});
app.get('/import/colors', (req, res) => {
...
});
app.post('/import/brands', (req, res) => {
...
});
app.post('/import/colors/:car_id', (req, res) => {
...
});
Express just attempts to match your routes in the order they are defined in your code for the type of request it is (.e.g GET, POST, PUT). So, if it's a GET request, Express matches only against the route definitions that include GET. Here's a few examples from the routes you show.
If there's an incoming route of /hello/there, then that will first match app.get('/:car/:eng', ...) because that matches ANY two segment path and it's the first route in order that matches.
If there's an incoming route of /import/colors, then that will also match app.get('/:car/:eng', ...) because that matches ANY two segment path.
If, on the other hand, you change the order of the code to this:
app.get('/import/colors', (req, res) => {
...
});
app.get('/:car/:eng', (req, res) => {
...
});
Then, /import/colors will match the first of these two routes because matching is tried in the order the routes are declared.
FYI, in general, I don't like using routes that have a top level wildcard because you get yourself all sorts of possible conflicts and you may find yourself boxed into a bit of a corner for future URL expansion when you want to add other routes.
Recommendation
So, if you have overlapping route definitions, then define the most specific routes first so they get a chance to match before the more general routes. Most of the time, I prefer a URL design that doesn't have overlapping routes and then you won't have this issue at all.
my dir structure
/src
--/public
--/server.ts
--package.json
--package-lock.json
above is my director structure
app.use(express.static(__dirname + "/public/"));
// app.use(express.static("/public/"));
const path = require("path");
app.get("/", (req, res, next) => {
// res.sendFile(path.join(__dirname, + "public", 'index.html'));
res.sendFile(__dirname , "index.html");
//res.send('Testing one two');
});
const port = process.env.PORT || '5005';
app.listen(port, () => console.log("Server running on port 5005"));
when I run the above code, it works well on my local machine but won't work when it is deployed to Heroku,
I tried just passing a string like this and it worked, but when I want to render a static file like the HTML file it wont work on heroku, any help? i think the problem is my directory structure
app.get("/", (req, res, next) => {
res.send('Testing one two');
});
If I recall correctly, express.static middleware is separate from res.sendFile. In other words, even if you set express.static to public, it will not do anything to res.sendFile, as it takes the first parameter as a path.
In my humble opinion, it would be better if you were to use an absolute path, like the following snippet below.
const path = require('path');
/** Code here... **/
app.get("/", (req, res, next) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
Explanations:
path.join is an utility to join path segments into one path. It is cross-platform compatible.
__dirname will get the current directory that the script is running from.
Further reading: Express methods.
You just need to give the address of the index.html file in the path for the code mentioned below and paste this code at the end of the inside of the express file and everything will work perfectly fine and you are good to go.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
var path = require('path');
app.use(express.static("public"));
app.get('/', (req, res) => {
res.sendFile(path.join('/index.html'));
});
app.get('/contact', (req, res) => {
res.send('contact');
});
app.get('/contact', (req, res) => {
res.sendFile(path.join('/index.html'));
});
First get works fine and gets the page. Second get works and displays a string at a different url...but when I combine the two (page that previously displayed and address that previously displayed something) it says Error: ENOENT: no such file or directory, stat '/index.html' . Any clues why this isn't working?
Part 2: do I need to use path and public directory, or is there a simpler way to send files directly from the project folder like a simple node server does?
I have loaded root route.
app.get('/', (req, res, next) => {
// loading an HTML page
});
We have loaded an HTML page where we have a submit button, submitting on this submit button, we load the "search" route.
This "/search" route is loading successfully, but we have to load some dynamic content and after fetching all data, we have to load another route like "/searchoutput"
When we call :
app.use('/searchoutput', router);
or
app.get('/searchoutput', router);
But nothing happens without any error.
Thanks
Kumar Anil
So, if I understood correctly, you could do something like this,
If it is a POST request:
app.post("/search", (req, res) => {
// some code
res.redirect("searchoutput");
});
app.get("/searchoutput" (req, res) => {
// some code
res.render("<your page>", { <yourResult>: <yourResult>);
});
If it is a GET request:
app.get("/search", (req, res) => {
// some code
res.redirect("searchoutput");
});
app.get("/searchoutput" (req, res) => {
// some code
res.render("<your page>", { <yourResult>: <yourResult>);
});
If you don't want to reload the page, you could use AJAX, calling onclick a function that receives data from express.
I am trying to make route dynamic like /review-{title}-{id}
, but causing error don't know why, Also if user enter the wrong params than how to handle that.
My client requirement is like above, I am not good in node and express please anyone suggested how to make routes like above.
Also if I needed to make route like this /review/:title/:id format than how can I make like that.
I am trying but it redirect me out to the 404 page,
Please find my existing code details inside,
server.js
this is working..
app.get('/review', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client/review.html'));
});
but not this one..
app.get('/review-*-*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client/review.html'));
});
Also not this one working
app.get('/review/*/*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client/review.html'));
});
This is 404 page which call evrytime while accessing dynamic pages
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client/404.html'));
});
Check out the syntax for routes in Express.
In most cases you're better off using route params, e.g.:
app.get('/review/:title/:id', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client/review.html'));
});
Some more flexibility (but more opaque for most developers) would be to match on regex.
I think you can put a * in the middle of words (they give an example like '/abc*def', but I'm not sure how nicely that plays with the other things you're doing, and I don't think you can have multiple *'s in the pattern if you do that.)