用node或者vscode开启一个简单的本地server服务器,加载html网页

使用Live Server

想要加载本地html页面可以快速能让它在你本地浏览器中打开,可以有好多种方式,如果你有使用vscode,可以安装一个插件:Live Server,然后直接在vscode中直接右键就可以开启这个服务:

安装好之后,在vscode中打开html,然后右键:就可以自动打开浏览器并加载你这个html页面

使用node搭建server服务

使用node.js自己写一个server服务,然后开启服务后,就可以返回本地的一个HTML页面:

javascript 复制代码
//加载必须的模块
var http = require('http')
var fs = require('fs')
var url = require('url')
var path = require('path')

//定位静态目录的位置,根据请求找出对应的文件
function staticRoot(staticPath, req, res) {
  var pathObj = url.parse(req.url, true)

  if (pathObj.pathname === '/') {
    pathObj.pathname += 'index.html'
  }
  //读取静态目录里面的文件,然后发送出去
  var filePath = path.join(staticPath, pathObj.pathname)
  fs.readFile(filePath, 'binary', function (err, content) {
    if (err) {
      res.writeHead(404, 'Not Found')
      res.end('<h1>404 Not Found</h1>')
    } else {
      res.writeHead(200, 'Not Found')
      res.write(content, 'binary')
      res.end()
    }
  })
}
//创建服务器
var server = http.createServer(function (req, res) {
  staticRoot(path.join(__dirname, '/'), req, res)
})
//监听8080端口
server.listen(80)
相关推荐
凉茶钱4 小时前
【c语言】动态内存管理:malloc,calloc,realloc,柔性数组
c语言·c++·vscode·柔性数组
hele_two8 小时前
VS Code + CMake 调用 SDL2 & SDL2_image 完整编译教程(Windows 平台)
c++·windows·vscode·图形渲染
secondyoung12 小时前
Markdown数学公式语法速查手册
算法·编辑器·markdown·latex
wjhx13 小时前
关于xcode中使用图标
ide·macos·xcode
web行路人13 小时前
Claude code在Vscode编辑器中使用整理
编辑器
漫随流水16 小时前
创建一个IDEA的Java项目
java·ide·intellij-idea
bigcarp16 小时前
IDE中AI辅助编程时禁止AI读取指定的文件或文件夹
vscode
且去填词17 小时前
VSCode 中使用 Codex:命令、Agent 与 Skills 完整指南
ide·人工智能·vscode·编辑器·codex
PersistJiao19 小时前
开发环境对比:VS Code、Cursor、IntelliJ IDEA
java·ide·intellij-idea
weixin_4520776419 小时前
VS code 使用STM32CubelDE for Visual Studio Code环境,如何配置CMakeLists.txt新增其他.C文件路径
c语言·vscode·stm32