简体   繁体   English

使用 http.createServer 的回调将两种不同类型的数据加载到网页

[英]Loading two different types of data to a webpage with http.createServer's callback

I'm trying to load an HTML page along with two separate CSS files through http.createServer()'s callback.我正在尝试通过 http.createServer() 的回调加载 HTML 页面以及两个单独的 CSS 文件。 Here's the important part of the code so far:到目前为止,这是代码的重要部分:

var server = http.createServer(function (req, res) {
  var htmlData = fs.readFileSync(__dirname + "/public/index.html");
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.write(htmlData);
  res.end();
}).listen(port);

When I try to load this, it also tries to load the CSS files linked within the HTML file.当我尝试加载此文件时,它还会尝试加载 HTML 文件中链接的 CSS 文件。 I've tried both adding direct links within the header and adding a script within the HTML file to add the links to the header, but neither work.我已经尝试在 header 中添加直接链接并在 HTML 文件中添加脚本以将链接添加到 header,但都不起作用。 How can I do this without putting the content of the CSS files directly within tags in the HTML file?如果不将 CSS 文件的内容直接放在 HTML 文件的标签中,我该如何做到这一点?

You are ignoring the request path and giving it the same file each time.您忽略了请求路径并每次都给它相同的文件。

You need to serve the right file based on the request.您需要根据请求提供正确的文件。

For example: if you want to serve two files index.html and style.css :例如:如果要提供两个文件index.htmlstyle.css

var server = http.createServer(function (req, res) {
  if (req.url === '/' || req.url === '/index.html') { // respond to both / and /index.html
    var htmlData = fs.readFileSync(__dirname + "/public/index.html");
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(htmlData);
    res.end();
  }
  else if (req.url === '/style.css') { // respond to /style.css
    var cssData = fs.readFileSync(__dirname + "/public/style.css");
    res.writeHead(200, { 'Content-Type': 'text/css' });
    res.write(cssData);
    res.end();
  }
}).listen(port);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM