jSutcliffe90 jSutcliffe90 - 2 months ago 7
HTML Question

Js File in Node & Express Showing a HTML file instead

I am trying to start my first Node, Express & Angular project but am currently having problems with the asset pipeline. I'm not sure if it is due to to my folder structure (I tried following online tutorials but am unsure if how it is set up is best practice so I'm happy for suggestions) but when I try an connect my js file it is instead loading the index.html. The error that I'm receiving is

Uncaught SyntaxError: Unexpected token <
.

Here is my server.js file:

// set up web server
var express = require('express');
var app = express();
var bodyParser = require("body-parser");

app.get('*', function (req, res) {
res.sendFile(__dirname + '/views/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

// listen (start app with node server.js)
app.listen(3000, function() {
console.log("server going");
});


I took a screenshot so you can see my folder structure, index.html file and the error message in more detail
enter image description here

All help is appreciated as I'm at a total loss on this one!

Answer

The browser asks for /public/js/app.js

The server runs this code:

app.get('*', function (req, res) {
  res.sendFile(__dirname + '/views/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

… since * matches anything, including /public/js/app.js, and sends it an HTML document.

You have to write the server so it gives the browser what the browser asks for instead of serving up index.html for everything.

Consider using the static module for this.