user5096599
user5096599

Reputation:

Node starts my server, so does gulp, but gulp doesn't find any paths

I am sure this is something small, but I am unable to figure it out. Node, nodemon and gulp use app.js to start my server so I am not sure why one way works while gulp does not. If I start my server using:

nodemon app.js or node app.js it starts fine and when I use the path localhost:1337 in the browser it does what it is supposed to do.

When I use the command:

gulp

it says that it started the server but when I navigate to localhost:1337 it does not display anything other than "Cannot GET /" and none of my sources are showing in the inspector. I still get the message that "the port is listening" as indicated in my app.js console.log. My gulpfile is as follows:

var gulp = require('gulp');
var nodemon = require('gulp-nodemon');

gulp.task('nodemon', function(){
    nodemon({
    script: './app/app.js'
    })

});

gulp.task('watch', function(){
    gulp.watch('*.js', ['nodemon']);
});

gulp.task('default', ['nodemon']);

my app.js file is:

express = require('express');
var app = express();

app.use(express.static('../views'));
app.use(express.static('../bower_components/angular'));
app.use(express.static('./directives'));

app.listen(1337);
console.log("The port is listening");

Upvotes: 0

Views: 1147

Answers (1)

peteb
peteb

Reputation: 19418

The 'Cannot GET /' being displayed when you go to localhost:1337 is Express's generic message when a request is made against a route that is undefined. A route needs to be defined for the pages that you want to serve. You need to add a Route to handle the request to the root of your app at http://localhost:1337/.

app.get('/', function(req, res) {
    // return back a message
    res.send('Welcome!');

});

Place the above snippet above app.listen() and the message "Welcome!" will be displayed.

To serve a view in an html file you need to add a view engine so Express knows how to render the file. Additionally, the views property needs to be configured so Express knows where to render your views from. The example below uses ejs to just handle plain html files and not worry about a template engine like jade.

app.use('views', path.join(__dirname + '/views'));
app.engine('html', require('ejs').renderFile);
app.use('view engine', 'html');

Now we can use the render function on the res object to send our index.html file:

app.get('/', function(req, res) {
  res.render('index');
});

This a guide from ExpressJS on how to implement routing in Express.

Upvotes: 1

Related Questions