javascript - CSS 和 JS 未在 Node.js 服务器上加载

标签 javascript node.js

我刚开始学习 Node.js,我写了这样一个最简单的服务器:

// workspace

const p = document.querySelector('p');
p.textContent = 'aleluja';
html {
	font-size: 10px;
}

body {
	font-size: 2rem;
}
<!DOCTYPE html>
<html lang="pl">
<head>

	<meta charset="utf-8">

	<title>Go go go</title>

	<link href="sheet1.css" rel="stylesheet">
	
	<script src="main.js" async></script>

</head>
<body>

	<p>something</p>
	
</body>
</html>

和服务器:

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

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('index.html', (err, html) => {
   if (err) {
     throw err;
   }
   const server = http.createServer((req, res) => {
     res.statusCode = 200;
     res.setHeader('Content-type', 'text/html');
     res.write(html);
     res.end();
   });
   server.listen(port, hostname, () => {
     console.log('started');
   });
})

我的问题是我第一次运行此代码时它运行良好 - css 和 js 加载没有问题。但后来我在同一台服务器上同时试验 PHP 和 Node.js(使用 nginx)。我失败了,因为我不太需要它(只是为了好玩)我放弃并更改了所有更改以实现此目标设置(如 nginx-conf 中的端口)。然后,在尝试再次运行此代码后,它不会加载 sheet1.css 和 main.js。为什么会这样?我将所有设置恢复为默认状态?

感谢您的回答。

最佳答案

这是你的服务器逻辑:

   const server = http.createServer((req, res) => {
     res.statusCode = 200;
     res.setHeader('Content-type', 'text/html');
     res.write(html);
     res.end();
   });

浏览器请求/,服务器给它html变量的值。

浏览器请求/sheet1.css,服务器给它html变量的值。

浏览器请求/main.js,服务器给它html变量的值。


需要注意req对象中的URL,给浏览器请求什么,而不是盲目发送html,不管请求什么。

请注意,您还需要设置正确的 Content-Type 响应 header 。

(您可能还应该避免重新发明轮子并使用为此设计的 Express.js 及其 static module)。


My problem is that first time I run this code it worked fine - css and js loaded without problems.

这不可能发生。可能您从 file: URL 加载了 index.html 并完全绕过了服务器。

关于javascript - CSS 和 JS 未在 Node.js 服务器上加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57512538/

相关文章:

javascript - 如何将 svg 放在 div 中

javascript - Chrome 扩展 : can't get message passing to work between background script and content script

javascript - 如何在react.js中执行子组件验证而无需无限循环

javascript - 正则表达式:跳过引号内的注释

javascript - Node.js:单变量,多个 Promise

javascript - 在 Sails.js 中使用 GruntFile 根据当前 Controller 加载 JS 文件

javascript - 使用 Jquery 在文本框上启用 Click 事件

node.js - 如何处理express nodejs中的body-parser错误

node.js - 带有 Express.js 的 SOAP 服务器

javascript - 带有 Javascript 同步接口(interface)的异步操作