在纯 node.js 上提供多种类型的文件

Serve multiple type files on pure node.js

我有一个简单的纯 node.js 服务器,它根据请求发回 html 页面。 在我的 html 页面中,我连接了 js 文件。 当我发出请求时,我得到 html 页面的响应,但没有 js 文件。 在我的控制台中出现错误。

Uncaught SyntaxError: Unexpected token '<'

我的 node.js 服务器文件:

const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', });
    fs.readFile('index.html', function(err, data){
        if(err){
          return console.log(err);
        }
      res.end(data);
    });
}).listen(8080);
console.log('Server is running on Port: 8080');

我的 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>here</h1>
    <script src="./app.js"></script>
</body>
</html>

关于如何使用纯 js 根据请求发送多个文件有什么建议吗?

您目前正在使用 index.html 处理所有请求,因此当浏览器请求 app.js 时,您没有获得脚本,而是获得索引页面,因此出现错误。

您需要检查服务器回调中的请求路径,然后发送正确的文件(有关更详细的示例,请参阅 this):

http.createServer(function (req, res) {
    if (req.path === '/app.js') {
       // read app.js file and send it to the client
    } else {
      res.writeHead(200, {'Content-Type': 'text/html', });
      fs.readFile('index.html', function(err, data){
        if(err){
          return console.log(err);
        }
       res.end(data);
    });
}).listen(8080);

你看这很麻烦,所以我强烈建议使用像 express 这样的框架(它提供了一个中间件来提供开箱即用的静态文件)来做到这一点。