How to render multiple html files in node js? [closed] - html

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 27 days ago.
Improve this question
enter image description here
this is my server.js file.
I built the server through express and succeeded in rendering the file list.html and css, but it is impossible to move from list.html to another html file by entering localhost:8080. I want to move the write.html, edit.html, and view.html that you see over there from the list.html that I searched for localhost:8080. Please teach me the way.
I've tried many different ways of searching on Google, but I haven't got the results I want. I want to finally make a crud bulletin board and my first goal is to make it possible to move smoothly in that html form now.

You can use routing for catching different routes/paths
https://expressjs.com/en/guide/routing.html
app.get('/', (req, res) => {
res.render('index.html')
})
app.get('/edit', (req, res) => {
res.render('edit.html')
})
app.get('/view', (req, res) => {
res.render('view.html')
})

You are using express.static('public'), which will serve all static assets (including html files) in the public folder. Try putting the files in the view folder, and the index.html, in the public folder.

Related

Creating two html pages in SAPUI5 and executing one or the other depends on the situation

Currently I have my project running as welcomFile the index.html file. This file takes me to an authentication process. The case is that I need to access one of my views but without performing this authentication, that is, I don't want to go through this index.html. To do so, I created another html (index_new.html). Even if I run this last one it always redirects me to the index.html, I don't know if it has to do with how the neo-app.json file is configured. I tried to put in the index.html that if it arrived a parameter in the url to be directed to the index_new.html but without success, it says that the page does not exist. This is what I tried:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
window.location.search = urlParams.toString();
const con = urlParams.get('con');
if (con !== ""){
window.open("/index_new.html", "_self");
}
</script>
The only way I have managed to load the path I want is to run the program, it goes to the index.html and once it has loaded, I change the path to the index_new.html/viewthatIwanttoshow and it shows up. Is there any way to run the new index_new.html without having to run the old one?
I also think it's because of the manifest, because from the index_new.html I do it like this, just like in the index.html:
……
<script id="sap-ui-bootstrap>
…
data-sap-ui-resourceroots='{"app.hello”: “./“}’
…
</script>
</head>
<body class="sapUiBody">
<div data-sap-ui-component data-name="app.hello” data-id="container" data-settings='{"id" : “hello”}’ style="height: 100%"></div>
</body>
Maybe I should change the path here but I don't know which one or how to configure it in the manifest.json.
Maybe my question is not clear, if you have any questions please let me know.
My neo-app.json:
"welcomeFile": "/webapp/index.html",
My manifest.json:
"sap.app": {
"id": “app.hello”,
"type": "application",
I can't / don't want to give you a direct answer on your question. But I would like to mention to think about the concept you are going for.
I don't really understand why you want to load different index.html files. It's pretty far away from a best practice scenario - at least with the information I have out of your post.
When we are talking about authentication, mostly you save a token in cookies / browser storage. Then you can check if you are authenticated. If so, use the UI5 router. In every page you want to, you can check for valid authentication / authorization and redirect again to a login page, if you are not.
IMO you shouldn't use two different index.html sites.
I hope this help you to find another way to solve it.

Can I link to a .ejs-page from a .html-page?

I am making a webpage and I have been looking on stackoverflow on how to link to .ejs-files from a .html-file.
People are saying the following
In index.html:
<li>Twitter</li>
In script.js:
app.get('/twitter',function(req,res){
res.render('twitter', { });
});
But it does not work for me. It says "Your file was not found". It works on localhost, but not when I first click on index.html and then click on twitter.ejs page from there. My code looks like this: jsfiddle.
twitter.ejs is in a view folders, while index is outside of this folder.
What is wrong?
The situation is you're trying to link directly to a view template.
You need to create a route to a twitter controller that then calls your template. It would look something like this:
router.get('/twitter', twitterController.twitter_view);
If your .ejs file is called "contact.ejs" as an example, then the route you're targeting may be something like "/contact".
First setup the contact route in your server code:
//Setting up the contact route
app.get("/contact", function (req, res) {
res.render("contact", {});
});
Update the href in the corresponding anchor tag to:
href="/contact"
I am using expressJS and EJS for this example. So these must be setup first.

Express loading images relative to url

I'm building a fairly basic webpage using express. However, I'm having some trouble with my image pathways.
This code works fine.
app.use(express.static(path.join(__dirname, "/app/public/")));
app.get("/overview", function(req, res) {
res.render('some-file');
});
Inside of some-file.ejs I have...
<img src="assets/images/picture.jpg">
But what doesnt work is when I have a second url pathway.
app.get("/overview/specific", function(req, res) {
res.render('another-file');
});
<img src="assets/images/picture.jpg">
In this example I'm trying to load the exact same image (in my case its a banner thats reused on every single page). This gives me an error that the image is not found. What I've noticed from the console errors is that the image is being loaded from localhost:3000/overview/assets/images/picture.jpg
I don't understand why express is trying to load the image from whatever the first pathway is (overview in this case). Overview shouldnt be in the pathway!
Can anyone help me out debugging this issue?
Thanks in advance
Try to use /assets/images/picture.jpg.
Add / before the path. Then it will take /app/public/ as a root and be sure that the image will be at :
/app/public/assets/images/picture.jpg
Now wherever you want picture.jpg just pass this absolute path.
We serve favicons dynamically using an ExpressJS redirect, it works very well.
First, we retrieve the site object from memory with a quick lookup based on req.hostname, then send this response:
res.redirect(site.favicon);
The favicon variable could be a static asset on our server, or an asset on another server too. Our front-end code just calls /api/resources/favicon and it will receive the correct link in return.

Using Onsen, how to write server side code in NodeJs that will render Jade files as HTML in a splitter

In my Onsen app I have the following splitter. I am using Jade, and rendering all the other pages from the list items in html (despite the fact that they are in separate jade files) by including the files at the bottom of the page, as shown below:
body(ng-controller='...')
ons-splitter(var='mySplitter')
ons-splitter-side(var='menu' side='left' width='220px' collapse swipeable)
ons-page
ons-list
ons-list-item(ng-click="root.load('home.jade')", tappable='')
| Home
ons-list-item(ng-click="root.load('search.jade')", tappable='')
| Search
... more list items
ons-template(id='home.jade')
ons-page(ng-controller='...')
ons-toolbar
.left
ons-toolbar-button(ng-click='mySplitter.left.open()')
ons-icon(icon='md-menu')
.center
| My App
//- google maps stuff
ons-input#pac-input.controls(type='text', placeholder='Search Box')
div#map.col-md-12
ons-bottom-toolbar
.center
| MyApp
include search.jade
I believe this is a dirty shortcut, and will load the contents of search.jade (as well as every other file I include) before the user even clicks the item in the splitter.
I do not want this functionality. I would like to instead have server code in NodeJs that renders the jade files in html when they are ready to be displayed to the user. Something like this:
jade.renderFile('search.jade')
This angular code is currently how I am loading the page from the item in the splitter:
mySplitter.content.load(page)
.then(function() {
$scope.pop = page;
mySplitter.left.close();
});
However I am very confused about how to write this in a node route. Do I just abandon the splitter function in angular?
Can anyone help clarify this for me and show me a clear example of how to write the node route to render the jade files as html each time they are loaded?
Please see solution 1 of the selected answer from this stack overflow post for a reference of what exactly I am trying to do: stack overflow post
I am currently using solution 2 from that post.
I believe this is the relevant code in server.js:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
However when I change jade to html, I receive the error:
Error: Cannot find module 'html'
All my front-end files in the views folder have .jade extensions and are written in jade.
Update
Here is how I am serving index.jade (which is in the views folder) in a file called index.js:
module.exports = function(app){
/* Get home page. */
app.get('/', function(req, res, next) {
res.render('index', { title: 'My App' });
});
}
This was my old route NodeJS route which is no longer being used because of the splitter:
// get user search page
app.get('/user/search', function(req, res, next) {
return res.render('searchForTrainer');
});
Hmm. Since your code seems relatively small I would guess that what it does may be just serving all your files from views and actually "rendering" them. So probably you are just failing to access them properly later on. Maybe you have a url like /search.html or /search (instead of /search.jade). Could you try to confirm whether you can access such a url?
Also is your index.jade file served in some other way like startingPoint: 'index.jade' or something similar or is it also located in the views folder?
Basically as long as your index file has the same treatment as your other views then everything should be fine.
Update:
With what you just provided we can see the way in which you are serving your index.
app.get('/', function(req, res, next) {
res.render('index', { title: 'Fitness App' });
});
The equivalent of that is exactly the same as what you said you had before:
app.get('/user/search', function(req, res, next) {
return res.render('searchForTrainer');
});
Here res.render is what converts your jade into html and then returns it to the client. Since the splitter is expecting html that means you shouldn't have made changes to the server when you started using it.
Here is how the process looks like:
Client | HTTP | Server
| |
content.load('page') → GET /page ↘
| | res.render('page') // convert jade to html
html is loaded ← 200 OK html content ↙
in splitter.content | |
TL;DR - if you use your old route everything should be fine. Just remember to change the page url in the splitter from search.jade to /user/search (or whatever the url for will be).

How to hide HTML and other Content in EJS and Node

Having a tough time doing a simple web site in EJS.
I have this set up in my server file:
//Use the .html extension instead of having to name the views as *.ejs
server.engine('.html', require('ejs').__express);
// This avoids having to provide the extension to res.render()
server.set('view engine', 'html');
//set up directory to serve css and javascript files
server.use(Express.static(__dirname, '/views'));
This works great. I have HTML files, I have graphics, I have CSS. I am serving it up with a simple controller that renders the page. Nothing dynamic in these pages. But I do want them protected with an id/password system, and only served up through Express.
The access works fine, I have an end point set up to serve them. I'm forcing log in in that end point. But the problem is, that if someone knows the actual path to those files, they can get at them. So, the access is localhost:8081/admin/documentation/. However, the files are at /views/app_documents. And by entering in localhost:8081/views/app_documents/file_name.html, they can download/view the content, without going through my controls. I moved the content out of views, and grab it in my code, and serve it up, but that doesn't work for images or CSS.
Any suggestions for how to get around this?
Well, the things you find out after the fact.
This:
server.use(Express.static(__dirname, '/views'));
Is very bad. It should be:
server.use(Express.static('./views'));
The way it was, you could download our code, also. So, server.js was available for download. Yikes.
Live and learn.
Still can download the content without going through my authentication, though.
In case anyone else wants to do this, took a while. There are a few problems, as you still need to be able to directly access JS libraries, images and CSS. I found my answer in enter link description here.
The following modifications to that code does the trick. UserIsAllowed checks my permissions system to see if they can access that folder. If they can, no harm, off you go. Otherwise, kill the attempt. They get ACCESS_DENIED back as a string. I can't just kill anyone not going through my code, because then the CSS and images would not work. But this functions nicely. I now am able to serve up content based on my custom permissions system, which is part of a bunch of other administration functions. I can also have multiple different areas based on the URL that are protected by different privileges.
// This function returns a middleware function. It checks to see if the user has access
var protectPath = function(regex)
{
return function(request, response, next)
{
if (!regex.test(request.url)) { return next(); }
userIsAllowed(regex,function(allowed)
{
if (allowed)
{
next(); // send the request to the next handler, which is express.static
}
else
{
response.end('ACCESS_DENIED');
}
});
function userIsAllowed(regex,callback) {
if (regex.test('documentation_website') && request.session.admin_me && _.contains(request.session.admin_me["privileges"],"view_server_documentation")) callback(true);
else callback(false);
}
};
};
server.use(protectPath(/^\/documentation_website\/.*$/));