应用程序生成 HTML 错误“意外的令牌”<'" when setting the src attribute to a js file

问题描述 投票:0回答:1

我正在尝试使用一个 .js 文件,该文件是使用 index.html 文件中的脚本标记中的 src 属性设置的。该应用程序使用 Node JS 启动服务器并提供此 index.html 文件。该文件似乎未加载,并且 Edge 浏览器调试器显示错误,指出“未捕获的语法错误:意外的标记”<' (at user.js:1:1)". When I click on the error, it takes me to a the first line of the index.html and not the user.js file, showing that the error occurs at !DOCTYPE html.

我在 user.js 文件和 index.html 文件中查找了任何语法错误,一切看起来都不错。我还将“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);
  }
}
javascript html node.js
1个回答
0
投票

您可能还需要通过 .use(express.static('js'))

 提供 
App.js

文件

https://expressjs.com/en/starter/static-files.html

© www.soinside.com 2019 - 2024. All rights reserved.