[javascript] 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 ?

This question is related to javascript angularjs node.js express

The answer is


You can also get this error message when you place an inline tag in your html but make the (common for me) typo that you forget to add the slash to the closing-script tag like this:

<script>
  alert("I ran!");
<script> <!-- OOPS opened script tag again instead of closing it -->

The JS interpreter tries to "execute" the tag, which looks like an expression beginning with a less-than sign, hence the error: SyntaxError: expected expression, got '<'


This problem occurs when your are including file with wrong path and server gives some 404 error in loading file.


The main idea is that somehow HTML has been returned instead of Javascript.

The reason may be:

  • wrong paths
  • assets itself

It may be caused by wrong assets precompilation. In my case, I caught this error because of wrong encoding.

When I opened my application.js I saw application error Encoding::UndefinedConversionError at /assets/application.js

There was full backtrace of error formatted as HTML instead of Javasript.

Make sure that assets had been successfully precompiled.


May be this helps someone. The error I was getting was

SyntaxError: expected expression, got '<'

What I did clicked on view source in chrome and there I found this error

Notice: Undefined variable: string in D:\Projects\demo\ge.php on line 66

The issue was this snippet of code,

$string= ''; <---- this should be declared outside the loop

while($row = mysql_fetch_assoc($result))
    {
        $string .= '{ id:'.$row['menu_id'].', pId:'.$row['parent_id'].', name:"'.$row['menu_name'].'"},';
    }

which fixed the problem.


Just simply add:

app.use(express.static(__dirname +'/app'));

where '/app' is the directory where your index.html resides or your Webapp.


I had this same error when I migrated a Wordpress site to another server. The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.


This should work for you. If you are using SPA.

app.use('/', express.static(path.join(__dirname, 'your folder')));
// Send all other requests to the SPA
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'your folder/index.html'));
});

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess. The solution was to add the correct path slashes in . Each situation is unique, but hope this helps someone.


I had same error. And in my case

REASON: There was restriction to that resources on server and server was sending login page instead of javascript pages.

SOLUTION: give access to user for resourses or remove restriction at all.


I got this type question on Django, and My issue is forget to add static to the <script> tag.

Such as in my template:

<script  type="text/javascript"  src="css/layer.js"></script>

I should add the static to it like this:

<script type="text/javascript" src="{% static 'css/layer.js' %}" ></script>

I solved this problem with my authenticated ASPNET application by adding WebResource.axd as a location on the web.config so that it's authorized for anonymous users

<location path="WebResource.axd">
  <system.web>
    <authorization>
      <allow users="?"/>
    </authorization>
  </system.web>
</location>

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!


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js