MEAN栈开发导入JS文件遇Uncaught SyntaxError: Unexpected token <错误求助
Fixing
Uncaught SyntaxError: Unexpected token < in MEAN Stack JS Imports Hey there, I’ve run into this exact issue when I was starting out with MEAN stack too—let’s break down what’s going wrong and how to fix it.
The Root Cause
That error happens because when your browser tries to load app/app.js, it’s actually getting your index.html file instead of the JavaScript file. Here’s why:
- Your
server.jssets up a catch-all route withapp.get('*', ...)that returnsindex.htmlfor any request that doesn’t match other routes. - Your static file service is mounted at
/static(app.use('/static', express.static(__dirname+'/public'))), but yourindex.htmlis trying to loadapp/app.jswithout the/staticprefix. So the server doesn’t recognize this as a static file request and falls back to returningindex.html. When the browser tries to parse HTML as JavaScript, it hits the<from<html>and throws the syntax error.
Step-by-Step Fixes
- Update your script tag in
index.htmlto include the/staticprefix, since that’s where your public files are served from:<html> <head> <script src="/static/app/app.js"></script> </head> <body> <div class="container"> <nav class="navbar navbar-dark bg-dark"> <span class="navbar-brand mb-0 h1">Navbar</span> </nav> </div> </body> </html> - Verify your file structure to make sure
app.jsis actually located atpublic/app/app.js—if the path is wrong, even the corrected URL won’t work. - Optional: Clean up your static path configuration using
path.joinfor better cross-platform compatibility (avoids issues with slashes on Windows vs. Unix):// Replace this line in server.js app.use('/static', express.static(path.join(__dirname, 'public')))
Test It Out
After making these changes, start your server and try visiting http://localhost:8080/static/app/app.js directly in your browser. If you see the console.log("testing"); line, your static files are being served correctly. Then reload your app—the error should be gone, and you’ll see "testing" in your browser’s console.
内容的提问来源于stack exchange,提问作者Mike3096
相关产品推荐
相关产品推荐

