微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

1.vwe开发之创建express后台服务器

构建一个express服务器

请参考Creating a Node Express-Webpack App with Dev and Prod Builds

你可以理解为这是翻译版。

  1. 创建一个项目叫 express-webpack

    1. 手动新建项目 express-webpack
    2. 在当前项目下执行下面代码
    mkdir express-webpack
    cd express-webpack
    
  2. npm初始化项目,生成package.json

    npm init -y   //-y 选择表示认是,跳过输出
    
  3. 安装 Express

    npm install --save express
    
  4. 创建一个Express Server

    在根目录下新建一个server.js,代码如下

      //引入需要的包
      const path = require('path')
      const express = require('express')
      //实例化一个express对象,用来创造一个http server
      const app = express(),
        disT_DIR = __dirname,   //__dirname表示当前脚本运行的根目录
        HTML_FILE = path.join(disT_DIR, 'index.html')
      app.use(express.static(disT_DIR))  //定义静态资源的入口
      //任何处api 请求都发送认入口页面
      app.get('*', (req, res) => {
        res.sendFile(HTML_FILE)
      })
      //定义服务器端口,参数传入的或者是8080
      const PORT = process.env.PORT || 8080
      //开启服务器端口的监听
      app.listen(PORT, () => {
        console.log(`App listening to ${PORT}....`)
        console.log('Press Ctrl+C to quit.')
      })
    
  5. 建立3中的入口页面,在根目录下建立index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <Meta charset="utf-8">
        <title>Express and Webpack App</title>
        <link rel="shortcut icon" href="#">
    </head>
    <body>
        <h1>Expack</h1>
        <p class="description">Express and Webpack Boilerplate App</p>
    </body>
    </html>
    
  6. 建立运行脚本,在package.json中加入脚本

     "scripts": {
       "start": "node ./server.js"
     },
    

    最后的package.json为

     {
       "name": "express-webpack",
       "version": "1.0.0",
       "description": "",
       "main": "index.js",
       "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1",
         "start": "node ./server.js"
       },
       "keywords": [],
       "author": "",
       "license": "ISC",
       "dependencies": {
         "express": "^4.16.4"
       }
     }
    
    

    当前目录如下:

    node_modules
    index.html
    package-lock.json
    package.json
    server.js
    
  7. 运行脚本,

       npm run start
    

    控制台输出如下:

    App listening to 8080....
    Press Ctrl+C to quit.
    

打开网页,输入地址:http://localhost:8080/
页面显示 如下:

Expack

Express and Webpack Boilerplate App

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐