I am using express with hoganjs templating instead of jade.
When I try to access one of my routes, it wont work though...
In app.js, I have the following (relevant to the route):
var awesome = require('./routes/awesome.js');
app.use('/awesome', awesome);
In the routes/awesome.js file, I have the following:
var express = require('express');
var router = express.Router();
/* GET awesome page. */
router.get('/awesome', function(req, res, next) {
res.render('awesome', { title: "awesome", message: "awesome"});
});
module.exports = router;
And lastly, here is my awesome template (located in ./views/awesome.hjs).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<meta name="Author" content="{{author}}"/>
<link rel="shortcut icon" href="" />
<!-- Bootstrap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron">
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}, here is your message: {{message}}</p>
</div>
</div>
</div>
</div>
</body>
</html>
I have basically the same code for the index route so why wont this one work too?
In awesome.js change the router path location to /
router.get('/', function(req, res, next) {
res.render('awesome', { title: "awesome", message: "awesome"});
});
Now localhost:3000/awesome should be available.
app.use('/awesome', ...) matches all the routes starting with awesome. Paths specified in router.get('/awesome', ...) acts as sub-paths. The path URL will be localhost:3000/awesome/awesome.
Related
I have a user route that render a form, now i wish to take data from the form using a post request, but when i attempt to do so, my req.body is {}. I've already tried using body parser but the result is the same one. I've also tried using the middleware of the encoded url in the app.js instead of the user routes, but that doesn't work ether.
const express = require('express');
const router = express.Router();
router.use(express.urlencoded({extended: true}));
const messages = [
{
text: "Hi there!",
user: "Amando",
added: new Date()
},
{
text: "Hello World!",
user: "Charles",
added: new Date()
}
]
router.get('/', (req, res) => {
res.render('index', {title: "Mini Messageboard", messages: messages});
});
router.get('/new', (req,res) => {
res.render('form')
})
router.post('/new', (req,res) => {
console.log(req.body) // {}
res.send(req.body)
})
module.exports = router;
my ejs file:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = 'text/css' href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,300;1,500&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<title></title>
<body>
<form method="post" action="/new">
<input placeholder ="Insert your name here" type="text" name="" id="">
<input placeholder = 'Insert youre message here' type="text">
<button type="submit">Submit</button>
</form>
</body>
</html>
The name attribute is responsible for forming key-value pairs in the body of a request. Provide a name attribute for input tags, like:
<input type="text" name="*your key*"> and then in backend: console.log(req.body["*your key*"]) will give you the value of input tag.
i want to encorporate my head and my body on handlebars, but i dont know how,
i will give an example on how im using it '''
<link rel="stylesheet" href="/css/index.css">
<h1> test</h1>
'''
the handlebars'''
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/nome.css">
<title>Documen</title>
</head>
<body>
{{{body}}}
</body>
</html>
'''
with this code im passing that every element go to this {{{body}}} right?
and i want to pass a head too, how do i do that?
really sorry if the question is confuse, i really dont know how to explain better
Firstly You need install npm install express express-handlebars.
Here you have folder and file project structure:
app.js
const express = require("express");
const exphbs = require("express-handlebars");
const app = express();
const PORT = process.env.PORT || 3000;
// view engine setup
app.engine(
"hbs",
exphbs.engine({
defaultLayout: "main",
extname: ".hbs",
})
);
app.set("view engine", "hbs");
app.get("/", (req, res) => {
res.render("home");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.listen(PORT, () => {
console.log(`Node Server running on port: http://localhost:${PORT}`);
});
main.hbs
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
{{>header}}
<div class="container d-flex justify-content-center align-items-center flex-column" style="height: 800px;">
{{{body}}}
{{>mainContent}}
</div>
{{>footer}}
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
</body>
</html>
header.hbs
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about">about</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
mainContent.hbs
<h2>Hello World from Handlebars</h2>
<h3>Express</h3>
<h4>Bootstrap 5</h4>
footer.hbs
<footer>
<p class="text-center text-muted">© Copyright 2021 The Awesome Stuff</p>
</footer>
home.hbs
<h1>Home Page</h1>
about.hbs
<h1>About Page</h1>
Output:
"express": "^4.17.1","express-handlebars": "^6.0.2"
Hello I use nodeJS and I want to create an application in which I want to make a post request with a Json object from Postman or curl, my app will fetch Json Object and it will appear the object in broswer.
So, I tried to do that , but I have the problem that the json Object don't appear on broswer
(I use npm hbs, but also I tried it without that).
my nodeJS code is:
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.use('/notify',(req,res)=>{
const json = req.body
console.log(json)
res.render('index' , {
title: 'Weather App',
name:'ApLaz',
expect: JSON.stringify(json) // I tried and without JSON.stringify
})
})
With Postman request I send for example that
{
"test": "ok",
"var": 12
}
The result from console.log is :
{ ok: 'ok', var: 12 }
But on the broswer I just take this:
{}
This is my website
Why I can't appear my Json Object on broswer?
This is my index file
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css">
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{{title}}</title>
</head>
<body>
<!-- Header -->
{{>header}}
<!-- End Header -->
<div>
<p>Use this site for the Weather</p>
<form id="formSearch">
<input placeholder='Location' id="inputSearchValue">
<button>Search</button>
</form>
</div>
<br>
<p id="location">{{expect}}</p>
<p id="forecast"></p>
<!-- Footer -->
{{>footer}}
<!-- End Footer -->
<script src="js/app.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
I don't have the info I need to exactly match your setup but here is a close approach. Keep in mind this is not how you would do it in a actually site but will work for learning.
You can think of dataStore as a temporary database that only exist while the app is running. In the index.html I commented out/disabled the following: header, footer, and as you didn't provided and I don't want to create them :D
I suggest you continue along the FreeCodeCamp path as it will cover data storage down the road.
package.json
{
"scripts": {
"start": "node src"
},
"dependencies": {
"express": "^4.17.1",
"mustache": "^4.1.0",
"mustache-express": "^1.3.0"
}
}
src/index.js
const mustacheExpress = require('mustache-express')
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views', __dirname + '/views')
let dataStore = {
expect: {user: 'jdoe', age: 30},
}
app.use('/',(req,res)=>{
res.render('index' , {
title: 'Weather App',
name:'ApLaz',
expect: JSON.stringify(dataStore.expect) // I tried and without JSON.stringify
})
})
app.use('/notify',(req,res)=>{
const json = req.body
console.log(json)
dataStore.expect = json
res.render('index' , {
title: 'Weather App',
name:'ApLaz',
expect: JSON.stringify(dataStore.expect)
})
})
app.listen(3000, (err) => {
if (err) return console.log(err)
console.log('server listening on port: %s', 3000);
})
src/view/index.html
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css">
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{{title}}</title>
</head>
<body>
<!-- Header -->
<!-- >header}}-->
<!-- End Header -->
<div>
<p>Use this site for the Weather</p>
<form id="formSearch">
<input placeholder='Location' id="inputSearchValue">
<button>Search</button>
</form>
</div>
<br>
<p id="location">{{expect}}</p>
<p id="forecast"></p>
<!-- Footer -->
<!-- >footer}}-->
<!-- End Footer -->
<!--<script src="js/app.js"></script>-->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
To start the app open a terminal and run yarn start or npm start
I am using angular along with node.
I am using routes to redirect page.
Onto my html page i have defined 2 links as:
<!DOCTYPE html>
<html >
<head>
<title>My Angular App!</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="../public/javascript/angular-route.min.js"></script>
<link data-require="bootstrap-css#*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script src="/webstorm1/app.js"></script>
<script src="../controllers/registration.js"></script>
</head>
<body>
<div ng-app="test">
<a ng-href="#/login">Login</a>
<a ng-href="#/register">Register</a>
</div>
<div ng-view></div>
</body>
</html>
and onto the app.js file i have defined the route as:
var test = angular.module('test', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
console.log('test');
$routeProvider.when('/register',
{
templateUrl: '/webstorm1/partials/register.html',
controller: 'registration'
});
$routeProvider.when('/login',
{
templateUrl: '../partials/login.html',
controller: 'login'
});
});
when i run the html file and click on register link, it prints the 'test', but doesnot show the page on browser.
Your <div ng-view></div> is outside of <div ng-app="test"> scope.
<div ng-app="test"> <!-- ng-app starts -->
<a ng-href="#/login">Login</a>
<a ng-href="#/register">Register</a>
</div> <!-- ng-app ends -->
<div ng-view></div> <!-- outside from ng-app -->
Simply put that ng-app="test" to some parent element like body or html to make all elements inside their scope.
I'm trying to implement a basic node-express angular app which includes an ng-include directive.
This is the structure of my app:
App:
server.js
package.json
public:
js
css
index.html
partials:
header.html
partial-about.html
partial-homt.html
The content of my server.js is the following:
var express = require("express");
var app = express();
var port = process.env.PORT || 8080;
app.configure(function () {
app.use(express.static(__dirname + "/public"));
app.use(express.logger("dev"));
});
app.listen(port);
console.log("App listening on port: " + port);
This is the content of my index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS UIRouter demo</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="./css/style.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
</head>
<body ng-app="MyApp">
<nav class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
DD test Angular-UI Router
</div>
<ul class="nav navbar-nav">
<li>Home</li>
<li>About</li>
</ul>
</nav>
<div ui-view></div>
</body>
</html>
However when I try to simplify index.html to this:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS UIRouter demo</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="./css/style.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
</head>
<body ng-app="MyApp">
<div ng-include="'./partials/header.html'" ></div>
<div ui-view></div>
</body>
</html>
With header.html obviously including:
<nav class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
DD test Angular-UI Router
</div>
<ul class="nav navbar-nav">
<li>Home</li>
<li>About</li>
</ul>
</nav>
It doesn't work, any ideas?
In order for Angular to take over (and on order for the directives to become effective), you need to initialize the module:
<head>
...
<script type="text/javascript">
angular.module('MyApp', ['ui.router']);
</script>
</head>