Javascript 如何在node.js中链接css文件
一般来说,我对node.js和js都是新手。我有一个简单的应用程序,它有一个styles.css,但我不知道如何在app.js上链接它 在Javascript 如何在node.js中链接css文件,javascript,html,css,Javascript,Html,Css,一般来说,我对node.js和js都是新手。我有一个简单的应用程序,它有一个styles.css,但我不知道如何在app.js上链接它 在index.html中,它有 这是node.js的我的app.js: const http = require('http'); const fs = require('fs'); const hostname = '127.0.0.1'; const port = 3000; fs.readFile('index.html', (err, html)
index.html
中,它有
这是node.js的我的app.js:
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('Server started on port ' + port);
});
});
那么,我应该如何修改app.js,以便它能够找到css文件呢?对于您返回index.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;
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();
res.statusCode = 200;
}
else if(req.url == '/css/styles.css'){
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('css/styles.css'));
res.end();
} else {
res.write("invalid request")
res.end();
}
});
server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});
});
如果您不局限于原始
node.js
,并且可以使用express.js
,那么您可以做些什么来服务静态文件
这是您的server.js
const express = require("express");
const app = express();
app.use(express.static("public"));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Your app is listening on port ${PORT}`);
});
然后创建一个文件夹并将其称为public,这就是所有客户端的位置
下面是一个完整工作示例的实时演示:您的请求处理程序总是使用
index.html
的内容进行响应。因此,当浏览器解析html时,它会请求css/styles.css
,服务器会再次向它发送index.html
。您应该区分对index.html
和css/styles.css
的请求,以相应地返回内容;您是否熟悉Express.js,或者需要在没有任何框架的情况下使用raw Node.js?