I am trying to add hbs template in my code but I am getting the errror that Failed to lookup view "index" in views directory
const express = require("express")
const path = require("path")
require("../src/db/conn")
const app = express();
const port = process.env.PORT || 3000;
const static_path = path.join(__dirname, "../public")
app.use(express.static(static_path))
app.set("view engine" , "hbs");
app.get("/" , (req,res)=>{
res.render("index")
})
app.listen(port , ()=>{
console.log("server is listening on port no 3000" )
})
this is my code and also i have created a views folder and a index.hbs file inside that folder
app.set("view engine" , "hbs");
After this line add
app.set("views" , "views");
Related
index.js
const path = require("path");
const express = require("express");
const exp = require("constants");
const dotenv = require("dotenv").config();
const port = process.env.PORT || 5001;
const app = express();
//enable body parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//set static folder
app.use(express.static(path.join(__dirname, 'pubic')));
app.use('/openai', require("./routes/openaiRoutes"));
app.listen(port, () => console.log(`Server started on port ${port}`));
so I have 1 file index.js and in the public folder I have index.html file.
I am referring index.html in index.js through the path but when I run my localhost on port 5001 I get an error
Browser error
In the console
sorry I misspelled my public folder. My bad
so I'm trying to make a simple "route system", that would handle requests and send them to a certain controller.
The problem is that I can't even handle any route, because I get
Cannot GET /
error in response.
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
const express = require('express')
const app = express()
// Route config
const routes = {
['/']: {
controller: 'index',
method: 'get'
},
}
// Load routes
const load = () => {
for (const route in routes) {
app[routes[route].method](route, (req, res) => {
// Do something
})
}
}
exports.load = load
You don't use your router file in app.js, try that:
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
app.use('/', router);
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) { res.send({ success: true }); });
module.exports = router;
It's useless and unreadeable create an array whit your all your routes.
My suggestion is to try use command by terminal express my_app for generate the base structure and try to use it or at least read for see how it's work.
You seem to be lacking the context for how the routing system works within Express.
As a starting point, please create a project with the below structure, and try creating your own route to ensure you have a grasp on how to utilize them properly.
Create a new project folder
cd into the project folder from within your terminal
run npm init -y
Run npm i express dotenv
Create a file named app.js in the root of your project folder and place the below code inside of it:
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json({limit: '30mb', extended: true}));
app.use(express.urlencoded({ extended: true }));
app.listen(process.env.PORT || 3000, () => {console.log('Server successfully started')});
app.get('/', (req, res) => {
return res.send('Hello, World!');
});
Create a new folder named routes
Create a new file named test.js and place it inside of the routes folder
Place the below code in the test.js file.
const router = require('express').Router();
router.get('/', (req, res) => {
return res.send('Hello from your custom route!');
});
module.exports = router;
Go back into your app.js file and add the below lines of code to the bottom of the file
const testRoute = require('./routes/test');
app.use('/test', testRoute);
In your terminal, run node app.js
Make a GET request to http://localhost:3000/test by navigating to it with your browser, or by using a REST client, such as Postman.
Once you have completed these steps, you should understand the basic concept of Express routing.
You can use the router combined with Express Middleware to re-route your user to the proper controller based on the endpoint they are trying to access / the data they are trying to send.
Please test with this code
const express = require('express')
const app = express();
app.get('/', (req, res) => {
res.json({"message": "Welcome! it's working"});
});
The complete code is here on Github
I set the homepage to login.html, but why does the homepage be index.html?
I tried to delete index.html. It turns out that the web shows login.html so I was wondering.
app.js
const express = require('express')
const bodyParser = require('body-parser');
const path = require('path');
const app = express()
const PORT = process.env.PORT || 3000
express.static('public')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'/public/login.html'))
})
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
public folder
public
---> css
---> img
index.html
login.html
In regards to serve-static, the documentation says:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
http://expressjs.com/en/resources/middleware/serve-static.html
In your example, you can disable this default behavior by setting the "index" option to "false":
app.use(express.static("public", { index: false }));
There is also an option to pass an array (as mentioned in the documentation):
app.use(express.static("public", { 'index': ['login.html', 'index.htm'] }));
I am new learning NodeJS + Express and now I am trying to build a simple register form but I keep getting the same error with this and other forms:
Cannot POST /registerauth
I have looked through dozens of similiar questions in stackoverflow and other sites but I have not found an answer that applies for my case.
Here is the form:
<form id="register-form" class="panel-form" action="/registerauth" method="POST">
<input type="text" name="register-username" id="register-username" class="fill-input" placeholder="Username *" autofocus="true" maxlength="15" required>
<input type="password" name="register-password" id="register-password" class="fill-input" placeholder="Password *" maxlength="30" required>
<button type="submit">Register</button>
</form>
My app.js file:
const express = require('express');
const app= express();
const path = require('path');
const port = process.env.PORT || 3000;
const login = require('./routes/login'); /*MODULE THAT HAS THE CONTROLLER CODE*/
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname , 'public')));
app.post('/registerauth',function (req,res,next){ /*TRIED THIS BUT DIDN'T WORK*/
console.log("testing");
res.json(req.body);
})
app.use('/login', login); /*TRIED CALLING THE MODULE THAT HAS THE CONTROLLER AND DELETING THE LINE ABOVE BUT DIDN'T WORK*/
app.listen(port, ()=> console.log(`server started on port ${port} `))
The module that has the controller code but it's not even called :
const express = require('express');
const oracledb = require('oracledb');
const router = express.Router();
const dbConfig =require('../dbconfig.js') ;
class Cliente{
constructor(username,password,nombre,email){
this.username = username;
this.password=password;
this.nombre=nombre;
this.email=email;
}
}
let conexion;
router.post('/registerauth',async(req,res,next)=>{ /*all this is not working neither*/
try{
console.log("THIS IS NOT WORKING");
cliente = new Cliente(req.body.username, req.body.password,req.body.nombre,req.body.email);
conexion= await oracledb.getConnection(dbConfig);
const result = await conexion.execute(
`INSERT INTO Cliente values (${cliente.username}, ${cliente.password},
${cliente.nombre}, ${cliente.email})`
);
} catch(err){
console.error(err);
}finally{
conexion.close();
}
})
module.exports = router;
And I have my project folder structured this way:
/
node_modules
public/
css/
media/
scripts/
index.html (just the file inside public folder)
register.html (just the file inside public folder THIS IS THE REGISTER FORM FILE)
routes/
api/
login.js
app.js
dbconfig.js
package-lock.json
package.json
Note: I created other forms in my project with different action methods and all of them gave the same error
this is the whole idea:
const express = require("express")
const app = express()
const router = require("./router")
app.use(express.static("public"))
app.use(express.urlencoded({extended: false}))
app.use(express.json())
app.use('/', router) // write all your routes in this file 'router'
module.exports = app
You need to render the HTML file in your server on port '3000'. I think you are trying to access 'http://localhost:3000/registerauth' directly while rendering the html page outside the server.
Make these changes to App.js file
const express = require('express');
const app= express();
const path = require('path');
const port = process.env.PORT || 3000;
const login = require('./routes/login'); /*MODULE THAT HAS THE CONTROLLER CODE*/
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
//newly added code
app.get('/',(req,res)=>{
res.sendFile('index.html');
})
app.post('/registerauth',function (req,res,next){ /*TRIED THIS BUT DIDN'T WORK*/
console.log("testing");
res.json(req.body);
// Redirect to '/login' here instead of sending response which will trigger the login module
})
app.use('/login', login); /*TRIED CALLING THE MODULE THAT HAS THE CONTROLLER AND DELETING THE LINE ABOVE BUT DIDN'T WORK*/
app.listen(port, ()=> console.log(`server started on port ${port} `))
Render the html page when you hit 'http://localhost:3000'. Also, inorder for your login component to work you need to redirect to '/login/' path in the POST request
I'm currently writing a web application with the MEAN stack, and am testing to see if my nodejs server is working. Here's my server.js:
// server.js
'use strict';
// modules =================================================
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
// expose app
exports = module.exports = app;
I currently have it redirecting all routes to my index.html file to test to make sure my views are working. Here's my routes.js:
// models/routes.js
// grab the user model
var User = require('./models/user.js');
module.exports = {
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
However, when I try to run node server.js, it gives me this error:
/home/hess/Projects/FitTrak/app/routes.js
app.get('*', function(req, res) {
^
SyntaxError: Unexpected token .
Does anyone have any idea what's causing this? I checked and all my braces and parentheses are all closed and written correctly.
As Jose Hermosilla Rodrigo said in his comment, you're declaring the object literal module.exports wrong. It should look like this instead:
module.exports = function(app) {
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
just try this code...
// models/routes.js
var express=require('express');
var app=express();
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
module.exports = route;
server.js
'use strict';
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var route=require('./models/route.js');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
app.use('/',route);
If you are using MEAN stack I would suggest you to use express own router middleware to handle all your routes. Just include.
var router = express.Router();
//use router to handle all your request
router.get(/xxx,function(req, res){
res.send(/xxxx);
})
// You may have n number of router for all your request
//And at last all you have to do is export router
module.exports = router;