Live Server扩展可一键启动本地HTTP服务器并支持热重载,适合前端快速开发;通过右键HTML文件选择“Open with Live Server”即可在http://127.0.0.1:5500预览。

在前端开发或静态页面调试时,经常需要快速启动一个本地 HTTP 服务器来预览文件。虽然可以直接打开 index.html,但某些功能(如 AJAX 请求、ES6 模块导入)要求资源必须通过 HTTP 协议加载。这时候,在 VS Code 中快速启动一个本地 HTTP/HTTPS 文件服务器就非常实用。
使用 Live Server 快速启动 HTTP 服务器
Live Server 是 VS Code 中最受欢迎的扩展之一,能一键启动本地开发服务器,并支持自动刷新功能。
操作步骤:- 打开 VS Code,进入扩展市场(快捷键
Ctrl+Shift+X) - 搜索并安装 Live Server(由 Ritwick Dey 开发)
- 右键点击你的 HTML 文件(如
index.html),选择 Open with Live Server - 浏览器会自动打开
http://127.0.0.1:5500/index.html,服务器已运行
默认端口为 5500,可在设置中修改。该服务器支持静态资源访问、热重载,适合前端开发调试。
使用 Node.js 手动启动 HTTP 服务器
如果你希望更灵活地控制服务器行为,可以使用 Node.js 创建一个简单的 HTTP 服务。
操作方法:- 确保已安装 Node.js
- 在项目根目录创建一个
server.js文件 - 写入以下代码:
const http = require('http');
const fs = require('fs');
const path = require('path');
const port = 8080;
const server = http.createServer((req, res) => {
let filePath = '.' + req.url;
if (filePath === './') filePath = './index.html';
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
};
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404);
res.end('404 Not Found');
} else {
res.writeHead(500);
res.end('500 Internal Server Error');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(port, () => {
console.log(`HTTP Server running at http://localhost:${port}/`);
});
- 在终端运行:
node server.js - 浏览器访问
http://localhost:8080
启用 HTTPS 服务器(可选)
若需测试 HTTPS 环境(如调用安全 API),可升级上述 Node 服务为 HTTPS。
操作步骤:- 生成自签名证书(使用 OpenSSL):
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
- 修改
server.js使用https模块:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, (req, res) => {
// 同上请求处理逻辑
}).listen(8443, () => {
console.log('HTTPS Server running at https://localhost:8443/');
});
- 运行后访问
https://localhost:8443,浏览器可能提示不安全,点击“继续访问”即可
基本上就这些。Live Server 适合日常快速开发,Node.js 自建服务则更适合定制化需求,包括 HTTPS 支持。选择合适的方式,提升本地调试效率。










