nodejs配置express服务器,放置文件,运行自动打开浏览器
来源:openlayers-cesium.com 时间:01-20
作为前端开发的项目,有的时候打包完后就想在本地测试是什么样子的,另外一些如cesium等程序,需要在服务的环境下才能启动三维球等。 这里使用nodejs+express搭建一个普通的服务器。
代码结构:
![](/uploads/2109/2_210929155940_1.png)
设置方法:
1,安装nodejs,参考:http://www.zjcopy.com/2021/0929744.html
2,创建一个文件夹,然后npm init 创建package.json
![](/uploads/2109/2_210929160529_1.png)
由于配置后来修改,main入口改为了server.js
3, 安装express和open组件
4, 配置server.js文件
- const express = require('express')
- const path = require('path')
- const app = express()
- const open = require('open') //npm另安装的模块
- app.use(express.static(path.join(__dirname, 'html')))
- open("http://localhost:7010") //打开网页
- app.listen(7010, () => {
- console.log('启动成功,请打开http://localhost:7010')
- })
5,package.json最终配置
- {
- "name": "express-server",
- "version": "1.0.0",
- "description": "nodejs 编写的express为框架的一个html服务器",
- "main": "server.js",
- "scripts": {
- "test": "test",
- "prestart": "echo " 启动start之前 "",
- "start": "node server.js",
- "poststart": "start http://localhost:7010"
- },
- "author": "zjcopy.com",
- "license": "ISC",
- "dependencies": {
- "express": "^4.17.1",
- "open": "^8.2.1"
- }
- }
6,放置文件:
将静态的文件放到
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>nodejs显示html</title>
- </head>
- <body>
- <h1>成功了,激动吗?zjcopy的访问者</h1>
- </html>
7,执行命令
开启服务,同时打开浏览器,浏览网页