• Ajax
  • Ant design
  • Axios-Fetch
  • Avue
  • Browser
  • Canvas
  • CSS
  • Dos-bat
  • Dva
  • Dedecms
  • Echart
  • ElementUI
  • Editors
  • Git
  • GeoServer
  • GIS
  • H5
  • Jquery
  • Java安卓
  • Json
  • Javascript
  • Leaflet
  • Linux
  • Life-Info
  • Mock
  • MongoDB
  • Network
  • NodeJS
  • NPM
  • React
  • 设计运营
  • SEO
  • SVG
  • TypeScript
  • Tools
  • umi
  • uni-APP
  • Vant
  • Vue
  • Windows
  • webpack
  • 位置:OC中文网 > 其他 > NodeJS >

    nodejs配置express服务器,放置文件,运行自动打开浏览器

    来源:openlayers-cesium.com 时间:01-20

     作为前端开发的项目,有的时候打包完后就想在本地测试是什么样子的,另外一些如cesium等程序,需要在服务的环境下才能启动三维球等。 这里使用nodejs+express搭建一个普通的服务器。

    代码结构:

    设置方法:

    1,安装nodejs,参考:http://www.zjcopy.com/2021/0929744.html

    2,创建一个文件夹,然后npm init 创建package.json

    由于配置后来修改,main入口改为了server.js

    3, 安装express和open组件

    npm install express open --save

    4, 配置server.js文件

    1. const express = require('express'
    2. const path = require('path'
    3. const app = express() 
    4. const open = require('open'//npm另安装的模块 
    5.  
    6. app.use(express.static(path.join(__dirname, 'html'))) 
    7.  
    8. open("http://localhost:7010")  //打开网页 
    9. app.listen(7010, () => { 
    10.   console.log('启动成功,请打开http://localhost:7010'
    11. }) 

    5,package.json最终配置

    1.   "name": "express-server", 
    2.   "version": "1.0.0", 
    3.   "description": "nodejs 编写的express为框架的一个html服务器", 
    4.   "main": "server.js", 
    5.   "scripts": { 
    6.     "test": "test", 
    7.     "prestart": "echo " 启动start之前 "", 
    8.     "start": "node server.js", 
    9.     "poststart": "start http://localhost:7010" 
    10.   }, 
    11.   "author": "zjcopy.com", 
    12.   "license": "ISC", 
    13.   "dependencies": { 
    14.     "express": "^4.17.1", 
    15.     "open": "^8.2.1" 
    16.   } 

    6,放置文件:

    将静态的文件放到html文件夹中,比如一个index.html文件

    1. <!DOCTYPE html> 
    2. <html lang="en"> 
    3.  <head> 
    4.  <meta charset="UTF-8"> 
    5. <title>nodejs显示html</title> 
    6. </head> 
    7.  <body> 
    8. <h1>成功了,激动吗?zjcopy的访问者</h1> 
    9. </html> 

    7,执行命令

    npm run start

    开启服务,同时打开浏览器,浏览网页