使用Express和Node将HTML、CSS和Javascript连接到服务器



我有HTML、CSS和Javascript程序可以完美地协同工作。我最近意识到我需要一台服务器来完成我的一些功能。我使用一些教程创建了一个本地Node服务器。在阅读了一些建议之后,我正在尝试使用Express尝试将HTML, CSS和Javascript添加到Node中,它们都在同一个文件夹中。下面的代码只是让浏览器保持加载状态。

const http = require('http');
const fs = require('fs').promises;
const host = 'localhost';
const port = 8000;
var express = require('express');
var path = require('path');
var app = express();
const requestListener = function (req, res) {
app.use(express.static(path.join(__dirname, 'public')));
//res.writeHead(200);
//res.end("My first server!");
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});

你不需要HTTP模块,如果你使用express…

const express = require('express')
const app = express()
// '/' is the url you want to host your site
// 'public' is the folder in which you have the necessary frontend files
// and the main html should be named as 'index.html' inside 'public'
app.use('/', express.static('public'))
app.listen(5000, () => console.log('server on port 5000'))

试试这个....

const express = require('express');
const app = express();
const path = require('path');  
app.use(express.static(path.join(__dirname,'css'));
app.use('/html',(req,res,next)=>{ 
res.sendFile(path.join(__dirname,'HTML','text.html');});
app.listen(3000);

最新更新