创建一个JavaScript项目
首先创建一个my-server文件夹,作为我们的js项目,项目包结构如下图所示:
server.js和public文件夹手动创建,package.json可以使用如下命令来创建
npm init
项目创建好之后,执行下面指令,安装需要的包
npm install
方案一:使用express模块
// 引入express
const express = require('express')
// 配置端口号
const PORT= 8080
// 创建一个app实例
const app = express()
// 配置静态资源(public目录下的静态文件)
app.use(express.static(__dirname + '/public'))
// 解决前端路由和后端接口冲突
app.get('*', (req, res) => {
res.sendFile(__dirname + '/public/index.html')
})
// npm i http-proxy-middleware,做代理
app.use(
'/dev',
createProxyMiddleware({
target: 'http://sph-h5-api.atguigu.cn'
changeOrigin: true,
pathRewrite:{'^/dev': ''}
})
)
// 绑定端口监听
app.listen(PORT,() => {
console.log(`本地服务器启动成功,http://localhost:${PORT}`
})
方案二:使用http和fs模块
const http = require('http');
const fs = require('fs');
const path = require('path');
const { createProxyMiddleware } = require('http-proxy-middleware');
const PORT = 8080;
// 创建服务器
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'public', req.url === '/' ? '/index.html' : req.url);
// 检查文件是否存在
fs.exists(filePath, (exists) => {
if (!exists) {
res.writeHead(404);
res.end('404 Not Found');
return;
}
// 检查文件是否为目录
fs.stat(filePath, (err, stats) => {
if (err) {
res.writeHead(500);
res.end('500 Internal Server Error');
return;
}
if (stats.isDirectory()) {
filePath += '/index.html';
}
// 读取文件并发送响应
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end('500 Internal Server Error');
return;
}
const ext = path.extname(filePath);
let contentType = 'text/html';
switch (ext) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
default:
break;
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
});
});
});
});
// 配置代理
const proxy = createProxyMiddleware({
target: 'http://sph-h5-api.atguigu.cn',
changeOrigin: true,
pathRewrite: { '^/dev': '' }
});
// 处理代理请求
server.on('upgrade', (req, res) => {
proxy(req, res, { target: 'http://sph-h5-api.atguigu.cn' });
});
// 绑定端口并启动服务器
server.listen(PORT, () => {
console.log(`本地服务器启动成功,访问地址:http://localhost:${PORT}`);
});
总结
只需要把前端框架(vue,react)打包好的静态文件,丢到public目录下,即可实现一个简单的前端静态资源服务器