Html redirection using Nodejs - javascript

I'm trying to link my back Node js api with my html pages .
for almost cases everything works well but I got confused at some point
What is the efficient way to follow in redirecting a html page because I usually use node js to do that like this which it seems to me wrong ? I think
res.sendfile('event.html')
but I saw in different page this statement which allows to jump from page to another
<div class="ui-block-title">
<h6 class="title">Events</h6>
Create New
</div>
could it possible to light on how to link the href part with node js backend ?
Best Regards,

Use Express.js a nodejs framework
Install & Include Express.js framework in your project
express = require("express"),
app.set("view engine", "ejs"); //setting all files view as .ejs
app.use(express.static("public"));
Now create a .ejs file and wrap it around html because at backend normal html can't be rendered
To wrap Do <%= > around each content object where you want to display some content
object
HomePage.ejs
<h1>HomePage!</h1>
Now call your html file using :-
app.get("/", function (req, res) { // no need to add .ejs as we had set all at ejs
res.render("HomePage");
});
// Output:
// HomePage!

probably you've got different routes in your node server, if you want to redirect to specific route you can just res.redirect('target') so if you're using express it would look sth like
const app = express()
app.get('/', (res, req, next) => {
res.render('index')
}))
app.get('/some-route' , (res, req, next) => {
res.redirect('/')
}))
app.listen(3000)
here if you go to main page the index page will be rendered, but it you go to foo.com/some-route you will be redirected to main page
thats in principle how redirection works with Node. Hope that this answers your question.

Related

Landing page keeps returning static files in express

I am trying to use static files in my project, but when the user makes a get request to my "/" landing page. I want to send non-static things like a json. But for some reason it just automatically sends my index.html in my static file.
const express = require("express");
const app = express();
app.use(express.static("public"));
app.get("/", (req, res) => { //This sends the user to the index.html even tho i want to send 123
res.send("123");
});
app.listen("3000");
As your code is written, the express.static() middleware looks at the / request, finds an index.html file in the public directory and serves that as the response for the / request. This is a feature of express.static() that is causing a conflict for you with your custom route for "/".
You have at least four choices for a solution here:
You can specify an option for express.static() to disable the index.html feature so it will avoid the "/" route and pass control on to your subsequent route handlers.
You can move the express.static() middleware AFTER your app.get("/", ...) route so that your custom route gets first dibs at the request.
You can remove the index.html file from your public directory so express.static() won't find it. Using a template system for all your HTML files that locates all HTML template files in some other directory that express.static() can't see (such as a views directory) would cause this to happen too or just moving it to some private directory and using it from your code from the private directory would work too.
Give ALL your static resources a common path prefix so there is never a URL conflict between static resources and custom route handlers.
The first option (disable index.html feature in express.static()) would look like this:
const express = require("express");
const app = express();
// disable index.html feature
app.use(express.static("public"), {index: false});
app.get("/", (req, res) => {
res.send("123");
});
app.listen("3000");
The second option (change the order of route definitions/middleware) would look like this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("123");
});
// put this after custom route definitions so they take precendence
app.use(express.static("public"));
app.listen("3000");
The fourth option (give all static resources a common path prefix) would look like this:
const express = require("express");
const app = express();
app.use(express.static("/static", "public"));
app.get("/", (req, res) => {
res.send("123");
});
app.listen("3000");
With this fourth option, you'd then have to prefix all your static URLs with the static prefix (which you can make anything you want) and thus "/" would never be a match for express.static().
Is there any particular reason that you have an index.html file inside your public directory and are serving something else? The convention is serve static assets such as CSS, JS, images etc. from your public folder, and HTML / templates in folder which would be a sibling of public such as views.
The browser will always default to rendering an index.html file if it is found in the root of the public directory. Move the HTML file to a separate folder and the route should work
app.use is a middleware, so whenever you're running a app, it always first go through the middleware, Try the below code
const express = require("express");
const app = express();
app.get("/", (req, res) => { //This sends the user to the index.html even tho i want to send 123
res.send("123");
});
app.use(express.static("public"));
app.listen("3000");

Node.js express and ejs trying to pass a variable from js file to ejs file

My folder structure is public-js-color.js and the ejs file is views-index.ejs
How do I pass a variable from the color.js file into the index.ejs file so I can display it to the user. Please forgive me if this is simple, just learning node and google has been no help.
when you define your express route and call render you want to pass to the view as the second parameter.
var variablesToPass = {
homie: 'who is your homie?'
};
app.get('/', function(req, res) {
return res.render('index', variablesToPass);
});
You will be able to render homie on your ejs home template by typing <%= homie %>
Also if you would like the variables to be available across your entire application a useful middlware function you could create is.
app.use(function(req, res) {
res.locals.homie = "I'm a homie thats available everywhere";
});

How to pass function required from another .js file into an index.ejs view via app.js

graphs.js: contains a function that makes an API call and returns an object with an HTML link that will be used to embed a graph.
app.js: contains the following (graphs.js has been required):
var express = require("express");
var app = express();
var graphs = require("graphs"); <---
app.use(express.static(__dirname + '/'));
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("index");
CAN I PASS THE FUNCTION THROUGH HERE?
});
//server
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Dev server started!");
});
index.ejs: I am attempting to pass the graphs.graph API function call through app.js so it is usable and executed in my index.ejs
For example:
<div class="graph-test">
<% graphs.graph() %>
</div>
Any advice, best practice comments, or any other methods of doing this would be greatly appreciated. Thank you!
No, you wouldnot send a function through res.render(). The practice is you deal which your logic/process in your route or controller first and then send only computed data into to template engine. It might be confusing some time as you can also write js in your template engine, but template engine only replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. Like below:
app.get("/", function(req, res){
var data = graphs.graph();
res.render("index", {data: data});
});
And talking about your specific problem, If your API call is done from server-side, then you should do like above. If your API call should be done through client-side then you can embed the js file into your view.

How can I serve my web app with Node/Express?

I'm probably going to ask a huge noob question, one of the worst I've ever had asked here, but I'm lost as hell with Node/Express. I've only used Apache servers (typical WAMP/XAMP for testing purposes), so I have absolutely no idea on what I have to do to serve my web app.
My folder tree is the following:
www
nodeserver.js
(more things)
Liteconomy (my web app)
js
css
plugins
templates
index.html
sublime_project
Pretty typical, huh? Well, I've been searching how to serve this app with a simple access like localhost:8080/Liteconomy, or localhost:8080/Liteconomy.html. After that, my angular routing would do the rest, but I just can't serve the app.
I've got this written in nodeserver.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
When I execute it and access to localhost:8080, I get the "Hello world", but when I go to localhost:8080/Liteconomy, I get the following plain text: "Liteconomy/index.html". If I try to access to the index resource directly, I get a "Cannot GET /Liteconomy/index.html" error.
I also tried using the static thingy, but didn't work either.
What am I doing wrong here? I guess I'm just missing something very important.
Do the following, it will resolve your issue.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// uncomment following if you want to access your app from /liteconomy
//app.use('/liteconomy', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
//This will enable you to access it form '/'
app.use('/', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
// Rest of the stuff
Then if you will visit your URL that you set and port, you'll be able to access.
Using express.static is recommended way of serving static content.
Hope it helps!
You get a plain text answer because you actually ask to do it with the :
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
If you want to send a simple html file like your index.html file, you should use the "sendfile " function :
app.get('/Liteconomy', function (req, res) {
res.sendfile(__dirname + '/Liteconomy/index.html');
});
"__dirname" represents your root directory path and then you simply put your file path.
Hope that helps !
PS : by default express come with jade and ejs template support instead of just using html. I would advise you to take a look at one of them, it can be a great help to construct your application web pages.

How to easily pass a variable with Node.js to the view

I'm trying to learn the basics of Node.js and I can't seem to be able to simply send a variable from app.js to index.html without using Jade or other template engine.
This is my app.js
var express = require("express");
var app = express();
app.get('/', function(req, res){
//I'd like to send this as a variable instead
res.send("some text");
});
app.listen(8080);
This is my index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//I want to alert my variable here please
alert(variableFromAppjs);
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>
Is there a way to do it simply like that?
The reason you can't just "send" the variable from your app.js to index.html is because they're two separate programs. index.html is run ONLY on the client machine through the browser, and app.js is run ONLY on the server.
In order for index.html to receive data from app.js, you'll need to to use XMLHttpRequest to make a request to your Node app.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
You can then receive the data asynchronously and save it to whatever variable you want.
You will need to make sure you're using a server-side templating engine (express comes with jade support).
Use npm to install jade to your express app. and then tell express where the templates are, and, in the get route definition you must instruct express what view to use:
var express = require("express");
var app = express();
// Tell express where your templates are
app.set("views", __dirname + "/views");
// Tell express templates are jade files
app.set("view engine", "jade");
app.get("/", function(req, res) {
res.render("home", {
title: "Home Page",
body: "This is just a test..."
});
});
app.listen(8080);
when all this is setup create views/layout.jade and a views/home.jade
Home.jade will look like this:
extends layout
block content
h1= title
p A tag name followed by the equals (=) sign is like php echo
p= body
ul
li This is a hardcoded list
li With two elements
Layout.jade will look like this:
html
head
meta(charset="utf-8")
title= title
link(rel="stylesheet", href="/css/main.css")
meta(name="viewport", content="width=device-width")
body
block content
div.page-content.text-center
h1 Default content
p anything I put here will be overridden by the home.jade content block Which means that any jade view that doesn't provide a `block content` part will render this text instead.
If you create another route for example:
app.get("/default", function(req, res) {
res.render("test", {title: "Default route", body: "Whatever"});
});
an then its corresponding template views/test.jade
extends layout
p I'm not providing a `block content` so this text won't be rendered
blockquote(class="my-class", id="my-id") In jade, the very first word of a line is the tag to be used by the line, to provide attributes to a tag you use comma-separated HTML attributes in between parenthesis right next to the tag name.
And visit your route at http://localhost:8080/default You will see the default text be rendered.
I hope this is of help.

Categories