0

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");

});

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.