0

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!

1 Answer 1

3

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.

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

1 Comment

Thanks Quentin, I have added app.use(express.static(path.join(__dirname, 'public'))); to server.js file and removed the app.get('*' route from the file and it's workinjg now. I found this blog about express.static which explains how to use it very well. Hopefully it might help some other noobs like myself in the future.

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.