gpt4 book ai didi

javascript - 在 HTML/CSS 中实现 Node Js

转载 作者:行者123 更新时间:2023-12-02 21:13:55 28 4
gpt4 key购买 nike

我正在使用 Nodejs 学习后端开发。从我到目前为止所看到的来看,似乎没有办法将它与使用普通 HTMLCSS 构建的已经制作的网站集成

有人告诉我,在运行 index.html 时本地文件没有 Nodejs ,Web 浏览器处理 css自动,但是使用 Node 时,如何同时获取 htmlcss显示?

我有一个HTML页面和我的 CSS 的 href文件。当尝试使用Nodejs时提出请求并服务我的 HTML页面时,它会显示没有样式的页面,并完全忽略 CSS我在 HTML 中引用的文件.

我已经尝试过express()ejs但是是否可以使用我已经用 HTML/CSS 制作的内容?

这是源代码,任何解释都会有很大的帮助:

const http =  require('http');//importing http
var fs = require('fs');//file stream

let handleRequest = (request, response) =>{
response.writeHead(200,{
'Content-type': 'text/html'
});
fs.readFile('./index.html', null, function(error, data){
if(error){
response.writeHead(404)
response.write('File not found!');
}else{
response.write(data);
}
response.end();
});

console.log('request was made: ' + request.url);//logg all requests made
}

http.createServer(handleRequest).listen(3000);

最佳答案

如果你想在 Node 应用程序中渲染 html。你有很多方法可以做到1.使用ejs pug等模板进行服务器端渲染

  • 您也可以使用不带模板的 html。但是您必须创建一个/public 文件夹,并在其中使用 fs 模块从 app.js 选择 index.html 的路径

  • 仅使用 Node 来制作 api,然后使用 vainlila html 或 vue 等框架从客户端调用它

  • 我建议开始 Node js 类(class)。

    关于javascript - 在 HTML/CSS 中实现 Node Js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61022550/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com