I'm trying to use express with Pug (Jade) to render/display a page and the function get() is coming back undefined with warnings...
I've run:
npm install express --save
npm install pug --save
Heres the top of the JS file with undefined get method...
var app = require('express')();
app.set('view engine', 'pug');
app.get('/', function (req, res) {
console.log("test"); //line isn't reached
res.render('index', { title: 'Hey', message: 'Hello there!' })
});
No errors when running, it just doesn't work.
You need to start the express server by
app.listen(9000, function(){
console.log('Server started...');
});
Add this line to the bottom of your JS file. Then open your browser and hit the url:
localhost:9000
Only then will the GET method call be invoked by express.
Related
total noob question but I cannot find any solutions to this sorry so last resort is to ask here.
I am trying to learn pug. Have created a boilerplate project and unable to render index page. Ive searched and read as much as I can but all I get is 'Error parsing body of the with expression' error. The index.js looks as simple as follows but stopping me in my tracks:
var express = require('express');
var router = express.Router();
// GET home page.
router.get('/', (req, res) => {
res.render('index', { title: 'Express' });
});
module.exports = router;
if anyone can provide a one liner to point me in the right direction to resolve this and keep rolling on my pug and nodejs journey I'd really appreciate it. Pug is appearing very difficult at this stage despite all the raving about it :/
I have checked one of my old projects. You can try something like this:
Install pug:
$ npm install pug --save
Then set up the app:
const express = require('express')
const app = express()
const port = 3000
// you don’t have to specify the engine or load the template engine module in your app;
// Express loads the module internally, as shown below (for the above example).
app.set('view engine', 'pug')
// views, the directory where the template files are located
// This defaults to the views directory in the application root directory.
app.set('views', './views')
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Example pug file:
html
head
title= title
body
h1= message
Using template engines
I am trying to run a script in my main index.js file from a script in the public folder. I do not know how to link the two.
I am trying to do this because I need to run file system operations on the server side. I have tried to link the script in the main HTML file, but when I try to run the function, it cannot be found.
my index file:
const express = require('express');
const bodyParser = require('body-parser');
var fs = require("fs");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile('public/index.html');
});
app.listen(3000, () => console.log('server started'));
function test() {
console.log("test");
}
my script in the public folder just has test();
my linking HTML
<script src="script.js"></script>
<script src="../index.js"></script>
I am expecting the test function to run, and log 'test'. It does not, and i get no console logs or errors.
All code is available on repl.it
People say the best feature of Node.JS is the ability to use the same code on the client and the server. However it isn't that simple.
You can't just include code in your HTML outside of the public folder. If you want to call a function on the server side, you will need to do something like this:
app.get('/test', (req, res) => {
test() // will log on the server side
res.send("All ok!");
});
And request that on the client side like so:
fetch('/test').then(res => {
console.log('got result from server!')
})
Essentially, you cannot just call functions on the server side - you have to talk to the server through HTTP. What you can do is create a shared folder with utility functions which you could include on both the client and server, but they couldn't be written with any reference to node modules unless you used a bundler (such as WebPack / RollUp).
you are confused with client side java script and server side node js file.
index.js is server side node js file. It has express link and runs like node index.js now if you want to use a java script function inside node js application you can use this example.
http://techslides.com/client-side-javascript-to-node-js
rest this line cannot be used for a nodejs server side js file.
You cannot run a function in your server script from another script which is running in the browser unless the function is set to be called via an end point. The server script and the browser script are not running in the same system so, they don't share the same execution context to call the functions in each other in a plain fashion.
Here is how you set the server function to be able to call from another system.
app.get('/runtest', (req, res) => {
test();
rest.status(200).send('Ok');
});
Now you can call this from your browser script via ajax.
You can't run a script in public folder in index.js in server-side. Because index.js is a script running in a server. This can't be include script in public folder which runs in the client(web browser). To run script.js in public folder you can create a new file in server with same name scirpt.js.
Script.js
module.exports = function test () {
// do some stuff
};
And import in index.js.
Index.js
const express = require('express');
const bodyParser = require('body-parser');
// import test function from script.js file in here
const test = require('./script.js');
var fs = require("fs");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile('public/index.html');
});
app.listen(3000, () => console.log('server started'));
// using it in here
test();
The const test = require('./script.js'); using to import function test from script.js file and using it in the last line test().
I have been following the a scotch.io tutorial to create my first node and angular app. I have seen that relative paths are a common issue online for the Error: ENOENT: no such file or directory which as far as I can tell is the same as the tutorial so I'm why its not working.
The full error message is:
Error: ENOENT: no such file or directory, stat'/Users/badman/githubRepos/travelGuide/app/public/index.html'
at Error (native)
My folder structure is here.
My server.js:
// set up web server
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
// routes
require('./app/routes.js')(app);
// listen (start app with node server.js)
app.listen(3000, function() {
console.log("server going");
})
routes.js:
module.exports = function (app) {
app.get('*', function (req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
Any help is appreciated :)
I had the same problem and I moved
app.get('*', function (req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
to server.js right under the require('./app/routes.js')(app); and that fixed it! Because it was looking for index.html in the wrong place when a server-side route was being called. I think you could have also changed the path too but I found this to be clearer.
Here are the dependencies of my package.json file where i've added "cool-ascii-faces. I then need to update my index.js file to GET the /cool page so that on each reload I would see an ascii face. I'm getting a 404 error and it says 'Cannot GET /cool'
"dependencies": {
"ejs": "2.3.3",
"express": "4.13.3",
"cool-ascii-faces": "~1.3"
}
Below is my index.js file that calls declares cool
var cool = require('cool-ascii-faces');
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/cool', function(request, response) {
response.render('pages/index')
});
app.get('/cool', function(request, response) {
response.send(cool());
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
I then run npm install to update the dependencies and then heroku local, but get the 404 error.
Any help in the right direction would be great!
You're probably getting an exception when you start the node web server, due to a module dependency error.
Check your command/terminal window. If you see a red warning message pointing to your module.js file, you have an exception:
$ heroku local
forego | starting web.1 on port 5000
web.1 | module.js:341
In this case, you need to install the cool-ascii-faces module. In your 'node-js-getting-started' directory, use the following npm command to install:
$ npm i -S cool-ascii-faces
Also... you'll want to convert your index page route back to '/'. Your routes logic should look like this:
app.get('/', function(request, response) {
response.render('pages/index')
});
app.get('/cool', function(request, response) {
response.send(cool());
});
Otherwise, you'll always get the default 'pages/index' page when you hit the '/cool' route instead of a smiley face.
You don't have to include
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
}
Heroku will run "npm start" to start your server and dynamically choose the port. You don't have to specify port explicitly.
this problem happened for me. After I typed "git push heroku master", I typed "heroku open" and it worked.
I have started a node js project and up to now I have included my html pages/css/etc in a folder named 'html'. I have npm- installed the relevat modules also. But some error message is displayed during the launch. plz help me out.Thnx
Project Hierarchy
squadra-server.njs
var express = require('express');
var app = express.createServer();
app.get('/', function(req, res){
res.send('Hello World');
});
app.configure(function () {
app.use(express.static(__dirname + '/html'));
})
app.listen(8000);
error msg
You have to configure the path to node.exe in your run configuration. Should not be much of a problem...