Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: expected expression, got '<'

I got SyntaxError: expected expression, got '<' error in the console when i'm executing following node code

var express = require('express'); var app = express(); app.all('*', function (req, res) {   res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */ }) var server = app.listen(3000, function () {   var host = server.address().address   var port = server.address().port }) 

Error :enter image description here

I'm using Angular Js and it's folder structure like bellow

enter image description here

What's I’m missing here ?

like image 557
underscore Avatar asked Mar 06 '15 07:03

underscore


2 Answers

This code:

app.all('*', function (req, res) {   res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */ }) 

tells Express that no matter what the browser requests, your server should return index.html. So when the browser requests JavaScript files like jquery-x.y.z.main.js or angular.min.js, your server is returning the contents of index.html, which start with <!DOCTYPE html>, which causes the JavaScript error.

Your code inside the callback should be looking at the request to determine which file to send back, and/or you should be using a different path pattern with app.all. See the routing guide for details.

like image 167
T.J. Crowder Avatar answered Oct 03 '22 16:10

T.J. Crowder


Try this, usually works for me:

app.set('appPath', 'public'); app.use(express.static(__dirname +'/public'));  app.route('/*')   .get(function(req, res) {     res.sendfile(app.get('appPath') + '/index.html');   }); 

Where the directory public contains my index.html and references all my angular files in the folder bower_components.

The express.static portion I believe serves the static files correctly (.js and css files as referenced by your index.html). Judging by your code, you will probably need to use this line instead:

app.use(express.static(__dirname)); 

as it seems all your JS files, index.html and your JS server file are in the same directory.

I think what @T.J. Crowder was trying to say was use app.route to send different files other than index.html, as just using index.html will have your program just look for .html files and cause the JS error.

Hope this works!

like image 41
devonj Avatar answered Oct 03 '22 15:10

devonj