javascript - 提供包含 CSS 的 HTML 文件

标签 javascript html css node.js server

我在名为 index1.html 的文件中有这段代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

<script src="./testing.js"></script>
<link rel="stylesheet" type="text/css" href="./formats.css" />

</body>
</html>

这是我的testing.js文件

$(document).ready(function(){
    $("p").click(function(){
        alert("The paragraph was clicked.");
    });
});

这是我的 formats.css 文件

body {
    color: blue;
}

p {
    color: green;
}

我使用此文件在本地主机上托管 html 文件。

var http = require ('http');
var fs = require('fs');
var path = require('path');
var port = '2406';

function send404Response(response){
  response.writeHead(404, {"Content_Type": "text/plain"});
  response.write("Error 404: Page not found!");
  response.end();  
}

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/'){
    response.writeHead(200, {"Content-Type": "text/html"});
    fs.createReadStream(path.join(__dirname, "index1.html")).pipe(response);

  } else{
    send404Response(response);
  }
}

http.createServer(onRequest).listen(port);
console.log("Server is now running on port 2406...");

当我在 Node 中运行 running.js 时,它不包含任何格式或当我转到本地主机时的 Jquery。我想知道为什么会这样,我可以做些什么来解决这个问题。

最佳答案

您的 onRequest 函数仅处理 1 个可能的 url“/”。

可以添加更多if 语句来处理不同的文件...

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/'){
    response.writeHead(200, {"Content-Type": "text/html"});
    fs.createReadStream(path.join(__dirname, "index1.html")).pipe(response);

  } else if (request.method == 'GET' && request.url == '/formats.css'){
    response.writeHead(200, {"Content-Type": "text/css"});
    fs.createReadStream(path.join(__dirname, "formats.css")).pipe(response);

  } else if (request.method == 'GET' && request.url == '/testing.js'){
    response.writeHead(200, {"Content-Type": "text/javascript"});
    fs.createReadStream(path.join(__dirname, "testing.js")).pipe(response);

  } else {
    send404Response(response);
  }
}

但您可能想研究像 express 这样的 HTTP 服务器框架。

关于javascript - 提供包含 CSS 的 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42819044/

相关文章:

javascript - Codeacademy 类(class)中的 Expect.js 验证问题

javascript - 如何告诉 IntelliJ 有关 javascript 事件属性的信息,以便它停止发出有关未定义属性的警告?

javascript - 自定义 jquery/js slider 动画

javascript - JavaScript 按位运算如何处理 NOT (~) 运算符?

JavaScript 文件在 Laravel 中无法正确加载

css - 如何在 css 中创建围绕 Png 图像本身的悬停

javascript - 如何使用javascript更改HTML文本字段的值

javascript - 如何动态操作 HTML 中的元素

css - masonry 网格图像顺序淡入

python - 尝试打印页面显示奇怪的布局