I'm creating a MEAN Stack application where angular has setup in /client folder. I want that when I run npm start command in /client folder it should render index.html file from /views folder, what I'm doing wrong getting this error
Cannot GET /
Folder structure is as follows.
meanApp
----- client (angluar2 setup here but doesn't have an index.html file)
---------- app
----- views
----------index.html
----- routes
----- server.js
Codes in server.js
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var index = require('./routes/index');
var tasks = require("./routes/tasks");
var app = express();
//View engines
app.set("views", path.join(__dirname,'views'));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Set static folder
app.use(express.static(path.join(__dirname,'client')));
// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/', index);
app.use('/index', index);
app.use('/api', tasks);
//listen
app.listen(3000, function(){
console.log("Server listing # 3000");
});
Here you need to define route for express server like :
app.set('appPath', 'client'); //this is a folder where your index.html is
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
This will cause every call in broweser to render index file.
const http = require('http');
fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();
app.set('appPath', 'views');
app.use(express.static(__dirname + '/views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use('/*', function(req, res, next) {
res.sendfile(app.get('appPath') + '/index.html');
});
http.createServer(app).listen(3001, function() {
console.log(`Express server listening on port 3001`);
});
exports = module.exports = app;
Related
I am using Node.js together with Express and EJS.
Below is my code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, 'public');
app.use(express.static(publicPath));
//app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/form_get.html', (req, res) => {
res.sendFile(__dirname + "/" + "form_get.html")
})
app.get('/process_get', (req, res) => {
console.log(req.query.first_name);
res.render(path.join(__dirname+'/views/thankyou.ejs'), { name: req.query.first_name});
})
var server = app.listen(3000, () => {
var host = server.address().address;
var port = server.address().port;
console.log(`Example app listening at ${host}:${port}`);
})
My folder structure is below:
mysql (folder)
node_modules (folder)
app4.js (file)
package.json (file)
public (folder, it contains form_get.html)
views (folder, it contains thankyou.ejs)
The problem is the failing to look up thankyou.ejs into the views folder.
I get the following error message:
Error: Failed to lookup view "thankyou.ejs" in views directory
".../mysql/views"
What can be the problem?
When You use app.set('view engine', 'ejs'); It is important to note that res.render() will look in a views folder for the view.
In this case
I mirrored Your project and it works fine with couple tiny changes...
Project Folder and file structure.
app.js
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.set("view engine", "ejs");
app.get("/form_get", (req, res) => {
res.sendFile(__dirname + "/" + "form_get.html");
});
app.get("/process_get", (req, res) => {
res.render("thankyou");
});
var server = app.listen(3000, () => {
var host = server.address().address;
var port = server.address().port;
console.log(`Example app listening at ${host}:http://localhost:${port}`);
});
Output:
http://localhost:3000/process_get (thankyou.ejs) file.
Output:
http://localhost:3000/form_get (form_get.html) file
I'm having some problems with express, I want to launch, by doing localhost:3000/timer -> timetimer.html, but it isn't working.
server.js:
var express = require('express');
var path = require('path');
var indexRouter = require('./routes/index');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use(function(req,res,next){
res.status(404).send('Richiesta Sconosciuta');
next();
});
app.listen(function () {
console.log('Server in ascolto sulla porta 3000!');
});
module.exports = app;
index.js:
var express = require('express');
var path = require('path');
var router = express.Router();
router.get('/principale', function(req,res){
res.sendFile('/principale.html', {root: path.join(__dirname,'../public')});
});
router.get('/timer', function(req,res,next){
//res.sendFile('public/timetimer.html', {root: path.join(__dirname,'../public')});
res.sendFile(__dirname + "/timetimer.html")
});
module.exports = router;
Structure of the folder:
The launch of the code works, i.e. it says that server.js is listening on 3000, but when I write localhost:3000/timer the browser is unable to reach the site
you didn't specify port in app.listen
try:
app.listen(3000, function () {
console.log('Server in ascolto sulla porta 3000!');
});
__dirname is the directory name of the current module.
So it is the routes folder.
timetimer.html isn't in the routes folder, so you're passing it a non-existent path.
I was using angular.js and I do this in express.js
app.get("*", function (req, res) {
res.redirect('/#' + req.originalUrl)
})
so that the browser will use the route of angular instead of express. But how to do that with react router? I have 2 folder, named server and client, server folder has express and api logic while client folder simply a react app.
You need to put the path in of the HTML file you are rendering your app to
app.get("/",(res,res) => {
res.sendFile('put the path of the html file you are rendering your app into here');
}
here is an example of a express server.js that works with react
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
app.use(express.static('./public'));
app.get('/', function(req,res){
res.sendFile('./public/index.html');
});
app.listen(PORT, function(){
console.log("Listening on port: " + PORT);
});
I have issue setting up routes for user in below code, I want to use express middleware and trying routes using app.use.
index.js is invoking user controller method once api's is being called So in below code i am trying to post data api/users from client but it returns 404.
How can i fix this issue using below routes setup ?
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
require('./config/express')(app);
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
app > routes.js
module.exports = function(app) {
app.use('api/users', require('./api/user'));
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
// res.sendFile(path.join(__dirname, ''../public/views/index.html''));
});
};
config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
// import cookieParser from 'cookie-parser';
// import errorHandler from 'errorhandler';
var path = require('path');
// import lusca from 'lusca';
var config = require('./db');
var mongoose = require('mongoose');
//var mongoStore = connectMongo(session);
module.exports = function(app) {
// app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
}
User index where i will handle all crud operation for user
app > api > user > index.js
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
router.get('/', controller.index);
router.post('/',controller.create);
module.exports = router;
1st:
To handle all request
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
app.use(function(req,res)
{
res.sendfile('./public/views/index.html');
console.log("Not found....I will handle *unhandle* rout here for you");
})
// app.get('*', function(req, res) use the above function instead of this
But this function at the end so it will only excute when no route path found to the app object.
Express documentation
2nd:
To handle createuser
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
// you must define route which you want to handle in user file
router.get('/api/user', controller.index);
router.post('/',controller.create);
module.exports = router;
Update working example with some explanation
Your app.js file
var express=require('express')
var app=express()
app.use('api/user',require('./user'))
app.use('/',require('./user'))
app.use(function(req,res)
{
res.sendfile('stack10.html')
console.log("Not found....I will handle *unhandle* rout here for you");
})
app.listen(8080,function()
{
console.log("server listening on port 8080")
})
user.js
var express = require('express')
var router = express.Router()
var app=express()
router.get('/api/user', function(req, res) {
res.send('respond for ..../api/user')
});
router.get('/',function (req,res) {
res.send('respose for ..../')
})
module.exports = router;
Your app.use will be app.use(api/user) while in user will be router.get(/api/user) so when u try http://127.0.0.1:8080/api/user
your response will be respond for ..../api/user
I'm a beginner in node.js but I try a little harder to setup a structure in node + express js.I start doing with the front-end and separate API structure.I put a single app.js for both API and front-end.But my API is not working. it gives error Cannot GET /api/users when i call http://localhost:3000/api/users. please help
api
-controllers
-helpers
-middlewares
-models
-routes.js
app.js
controllers
helpers
middlewares
models
node_modules
package.json
public
views
app.js
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000
var path = require('path');
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(require('./controllers'))
var routes = require('./api/routes');
app.use('/api', routes);
app.listen(port, function() {
console.log('Listening on port ' + port)
})
routes.js
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
module.exports = function (app) {
app.get('/users', usersController.getUser);
};
module.exports = router;
users.js(controller)
module.exports = {
getUser: function (req, res) {
console.log("sdfdsfdsfsd");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({"msg": "welcome user"}));
}
}
In your routes.js file you are exporting two things. Try to only export the router
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
router.get('/users', usersController.getUser);
module.exports = router;