ng-include is not working with node.js server - javascript

I have create a simple page using angular.js and node.js server, ng-include is not working.
console error: 404 (not found)
index.html
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<div ng-include="'views/header.htm'"></div>
<h1>heading one</h1>
</div>
</body>
</html>
header.htm
<h1>heading one</h1>
server.js
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/' + 'index.html');
console.log("----------------");
});
app.listen(3000);
OutPut
heading one

404 indicate the file is not existing. make sure the HTML file exist in given path. Also, there is a typo error. should be views/header.html
<div ng-include="'views/header.html'"></div>

I am not sure if it is the right way but it works. Add another get method for the html file which is to be included.
index.html
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<div ng-include="'/header'" method="GET"></div>
<h1>heading one</h1>
</div>
</body>
</html>
server.js
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/' + 'index.html');
console.log("----------------");
});
app.get('/header', function(req, res){
res.sendFile(__dirname + '/' + 'header.html');
console.log("----------------");
});
app.listen(3000);
If any suggestions/corrections/better methods, I would like to know please.

Related

Node.js/Express.js request body is undefined. body-parser is installed and imported

I am trying to get the text that is typed in by the user in my html input field and push it into an array. But the body of my request ist always empty. I already tried changing the order of code but it is not helping. Where is the Problem?
app.js file:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const gameRouter = require('./routes/game.js');
const siteRouter = require('./routes/site.js');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/game', gameRouter);
app.use('/', siteRouter);
app.listen(3000);
game.js file in the folder routes:
const express = require('express');
const router = express.Router();
const games = [];
router.get('/game', (req, res, next) => {
});
router.post('/create', (req, res, next) => {
console.log(req.body);
games.push({game: req.body.game})
res.redirect('/');
})
module.exports = router;
ejs file for html generating:
<%- include('./includes/head.ejs') %>
</head>
<body>
<%- include('./includes/nav.ejs') %>
<h1>Create a new Game</h1>
<main>
<form action="/game/create" method="POST">
<div>
<input type="text" id="game">
<button type="submit">start</button>
</div>
</form>
</main>
<%- include('./includes/end.ejs') %>
You need to add name attribute to the input element:
<input type="text" name="game" id="game">
Use this line before app.use():
// For parsing a JSON file
app.use(bodyParser.json())
// For parsing parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

localhost | wrong path to file | JS

A couple days ago I started learning Node JS and after couple hours I opened my localhost and it didn't have any css or JS, because of that the wrong path to files that I wrote. Could someone tell me what exactly I need to write in path, so the localhost won't give error like GET http://localhost:3000/index.js net::ERR_ABORTED 404 (Not Found)
// MY NODE JS CODE:
const express = require('express')
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
})
app.use('/static', express.static(__dirname + '/public'));
io.on('connection', function(socket) {
console.log('connected');
socket.on('disconnect', function() {
console.log('disconnected');
});
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
<!-- MY INDEX HTML CODE: -->
<link href="styles.css"> <!-- 1 link -->
<script src="index.js"></script> <!-- 2 link -->
<div id="something"></div>
Just change
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
})
app.use('/static', express.static(__dirname + '/public'));
into
app.use(express.static(__dirname + '/public'));

How to parse POST response body in Node

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.get(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
console.log(req.body.crypto);
});
app.listen(3000, function(){
console.log("server is running in port 3000");
});
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.get(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
console.log(req.body.crypto);
});
app.listen(3000, function(){
console.log("server is running in port 3000");
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Bitcoin ticker</title>
</head>
<body>
<h1>Bitcoin Ticker</h1>
<form action="/" method="post">
<select name="crypto">
<option value="BTC">Bitcoin</option>
<option value="ETC">Ethereum</option>
<option value="LTC">Litecoins</option>
</select>
<select name="fiat">
<option value="USD">US Doller</option>
<option value="GBP">GB Pounds</option>
<option value="EUR">EU Euroes</option>
</select>
<button type="submit" name="button">Check</button>
</form>
</body>
</html>
have an issue in javascript code when iam requesting for post request the browser says Cannot read property 'crypto' of undefined
when iam running the code there is no error but when iam selecting cannot read
property "crypto"
and i think the errror might be in here
console.log(req.body.crypto);
Your req.body is undefined,
you have to make this line
app.get(bodyParser.urlencoded({extended: true}));
to
app.use(bodyParser.urlencoded({extended: true}));
Looks like your req.body is undefined.
Guess the problem is with the body-parser.
Try changing this line
app.get(bodyParser.urlencoded({extended: true}))
To
app.use(bodyParser.urlencoded({extended: true}))
Instead of applying body-parser with app.get, do it with app.use
Subburaj and Ron537 are both correct because body-parser is a middleware and in express you use the method use to include a middleware to your express program. in your case to include the body-parser module/middleware in your app, do app.use(bodyParser.urlencoded({extended: true})) if you want to be posting both sub-document and app.use(bodyParser.urlencoded({extended: false})) if you dont want to be posting sub document

Node js : Using Handlebars and Bodyparser together

In this basic program I would like to get user input using 'body parser' and then enter that input via handlebars onto the index page. I have attempted many times but can't seem to acheive it. Also does handlebars and bodyparser go together or should I be using something different.
Template:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<header>
<h1>Bodyparser and Handlebars</h1>
</header>
<form method="post" action="/">
<input type="text" name="name1">
<input type="submit" value="Submit">
</form>
{{test}}
</body>
</html>
Node.js
var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var path = require("path");
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', 'html');
app.engine('html', handlebars({
defaultLayout: 'base',
extname: '.html'
}));
app.use(express.static(path.join(__dirname, 'public'))); //public directory
app.get('/index', function(req, res) {
res.sendFile('index.html', { root: __dirname });
});
app.get('/', function (req, res) {
res.render('index', {
test: req.body.name1});
});
app.post('/', function(req, res){
console.log(req.body.name1);
});
app.listen(3000);
Your post to / should be:
app.post('/', function(req, res){
res.render('index', {
test: req.body.name1});
});
And you are done.
Body-parser and handlebars work perfect togheter. Body-parser allows you to collect the request data inside the router controller and handlebars is a template engine that render the variables and more stuff.
You need to pass the text that you want to display to the POST router controller.
<form action="/" method="post">
name1: <input type="text" name="name1"><br>
<input type="submit" value="Submit">
</form>
Put that form in other view or anywhere you want
Inside the controller pass the request parameter to handlebars:
app.post('/', function(req, res){
res.render('index', {
test: req.body.name1});
});

node.js variables will not be parsed

i am new in node.js and express.
in my test app the html variables will not be parsed.
what is the problem?
server.js
enter var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.render('index', {
wert : 'hallo'
});
});
app.post('/', function(req, res) {
var wert = req.body.wert;
var html = 'Hallo: '+wert+'!\n'
+ 'Mach\'s nochmal!';
res.send(html);
});
app.listen(8882);
console.log('Server port: 8882');
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Startseite</title>
</head>
<body>
<p>Hallo <%= wert %>, dies ist mein kleiner Webserver!</p>
<br>
<form action="/" method="post">
<input type="text" width="40" name="wert" value="<%= wert %>">
<input type="submit" value="submit">
</form>
</body>
</html>
the value parameter <%= wert %> in the view is not parsed.
why? how to do it?
thank you
jet
Express doesn't come with a view-engine by default. You need to add one, in your case EJS.
Using the command line, type:
npm install ejs
server.js now becomes:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.render('index', {
wert: 'hallo'
});
});
app.post('/', function(req, res) {
var wert = req.body.wert;
res.render('index', {
wert: wert
});
});
app.listen(8882);
thank you ben,
your ejs configuration was good.
I had to install express, ejs, body-parser. that was ok.
then i had to remove the line with app.use(express.static(__dirname));
and i had to change
app.set('views', __dirname + '/views');
to
app.set('views', __dirname);
for my original path.
then everything was ok!
greez
jet

Categories