You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express服务器引入JS文件时出现"Unexpected token '<'"错误求助

Express服务器返回HTML而非JS文件导致脚本加载失败

问题描述

在index.html的script标签中通过src属性引入user.js文件,使用Node.js+Express启动服务器提供资源,但JS文件未成功加载。Edge浏览器调试器提示:

Uncaught Syntax Error: Unexpected token '<' (at user.js:1:1)

点击错误跳转至index.html的<!DOCTYPE html>行,说明请求user.js时服务器返回的是HTML内容而非JS文件。已检查user.js和index.html的语法,修改script标签的type属性(设为text/javascript、text/js或移除)均无效。

相关代码

App.js

const express = require('express');

const server = express()
  .use((req, res) => res.sendFile('/index.html', { root: __dirname }))
  .listen(3000, () => console.log(`Listening on ${3000}`));     

const { Server } = require('ws');

const ws_server = new Server({ server });

ws_server.on('connection', (ws) => {
  console.log('New client connected!');

  ws.on('close', () => console.log('Client has disconnected!'));
});

index.html

<!DOCTYPE html>
<html lang="en-US">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Today's Date</title>
    <script charset="UTF-8" type="text/javascript" src="./js/user.js"></script>    
</head> 
 
<body>
    <script>
        let user = new User('Billy');
        user.sayHi();       
    </script>        
</body>
</html>

User.js

class User {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    alert( this.name );
    console.log(this.name);
  }
}

问题原因

你的Express服务器配置中,使用了一个匹配所有请求的中间件:

.use((req, res) => res.sendFile('/index.html', { root: __dirname }))

不管浏览器请求的是/(首页)还是/js/user.js,服务器都会返回index.html的内容。浏览器尝试把HTML内容当作JS解析,自然会出现语法错误(因为HTML的第一个字符是<)。

解决方案

1. 调整项目文件结构

创建public文件夹作为静态资源根目录,将js文件放入public/js子目录,最终结构如下:

你的项目目录/
├── App.js
├── index.html
└── public/
    └── js/
        └── User.js

2. 修改App.js配置

先添加express.static中间件托管静态资源,再处理首页请求:

const express = require('express');

const server = express()
  // 托管public目录下的静态资源
  .use(express.static('public'))
  // 仅当请求根路径时返回index.html
  .get('/', (req, res) => res.sendFile('/index.html', { root: __dirname }))
  .listen(3000, () => console.log(`Listening on ${3000}`));     

const { Server } = require('ws');

const ws_server = new Server({ server });

ws_server.on('connection', (ws) => {
  console.log('New client connected!');

  ws.on('close', () => console.log('Client has disconnected!'));
});

3. 验证

重启Express服务器,刷新浏览器页面。此时浏览器请求/js/user.js时,服务器会返回对应的JS文件内容,User类可以正常实例化并调用sayHi()方法。

内容的提问来源于stack exchange,提问作者wachauski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 07:18:13