提问者:小点点

Node.js服务器无法正确提供文件


我正在尝试向浏览器提供html文件,该浏览器还通过加载简单的javascript文件。当我运行server.js并检查它应该服务的端口时,script.js不会加载。我做错了什么?

服务器代码

const http = require('http');
const fs = require('fs');
const port = 8080

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type':'text/html'});
  fs.readFile('./index.html', function(error, data) {
    if (error) {
      res.writeHead(404)
      res.write('Error:File Not Found')
    } else {
      res.write(data)
    }
    res.end(); 
  })
})

server.listen(port, (error) => {
  if(error) {
    console.log('Something went wrong', error)
  } else {
    console.log('Server is listening on port ' + port)
  }
})

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>
</head>

<body>

</body>

<script src="./script.js"></script>

</html>

共1个答案

匿名用户

这很容易,您只提供index.html。要服务其他文件,您需要修改您的代码,以便在服务文件之前检查请求的是哪个文件。

如何实现它的简单例子:

const http = require('http');
const fs = require('fs');
const port = 8080
var path = require('path')


const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type':'text/html'});
  let url = new URL(req.url, 'https://example.org/'); 
  // req.url is a relative address, 
  // but URL only works with relative addresses, if we provide
  // "base" address. So we provide it a fictional one,
  // it doesn't really matter in our case.
  let fileToRead = url.pathname
  if (fileToRead=== '/') fileToRead = '/index.html'
  fs.readFile(path.resolve(`./static/${fileToRead}`), function(error, data) {
    if (error) {
      res.writeHead(404)
      res.write('Error:File Not Found')
    } else {
      res.write(data)
    }
    res.end(); 
  })
})

server.listen(port, (error) => {
  if(error) {
    console.log('Something went wrong', error)
  } else {
    console.log('Server is listening on port ' + port)
  }
})

请注意,文件现在应该存储在静态目录中。向Web资源的用户公开代码从来都不是一个好主意;)