nodejs服務器部署教程二,把vue項目部署到線上

nodejs服務端部署教程一,https://segmentfault.com/a/11...
這篇文章主要介紹如何在服務端跑vuejs的項目,若是上一篇教程你成功輸出了hello world,那這一篇更簡單
首先你要有一個已經能在本地跑的基於vuejs的項目,我就以以前寫的仿餓了麼的項目爲例來部署,若是你尚未已經寫好的項目,能夠用個人這個項目來學習,https://github.com/wmui/vue-elm
此次部署就用最古老最省心的方法,ftp來上傳項目html

項目打包

npm run build後會有一個dist目錄,這個文件夾就是咱們要部署上線的項目vue

寫一個小腳本

若是你會點nodejs,腳本就很好理解了,下面是app.js啓動腳本的內容node

const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
// 模擬數據,api服務
var appData = require('./data.json');
var seller = appData.seller;
var goods = appData.goods;
var ratings = appData.ratings;
// api接口
var apiRoutes = express.Router();
apiRoutes.get('/seller', function(req, res) {
    res.json({
        erron: 0,
        data: seller
    })
});

apiRoutes.get('/goods', function(req, res) {
    res.json({
        erron: 0,
        data: goods
    })
});

apiRoutes.get('/ratings', function(req, res) {
    res.json({
        erron: 0,
        data: ratings
    })
});
app.use('/api', apiRoutes);
app.use(express.static(path.resolve(__dirname, './dist')))

app.get('*', function(req, res) {
    const html = fs.readFileSync(path.resolve(__dirname, './dist/index.html'), 'utf-8')
    res.send(html)
})
app.listen(8082);

簡單解釋一下上面的代碼,因爲項目須要些數據,個人模擬數據都在data.json這個文件裏,全部簡單的寫了三個路由,對應獲取到模擬數據。而後把dist目錄靜態出來,讀取dist目錄下的index.html(由於是單頁應用,只有這一個html文件),監聽8082端口nginx

咱們先在本地把要上傳的文件都準備好:
咱們的這個腳本使用了express框架,因此咱們能夠生成一個package.json,把依賴項添加進去git

{
  "name": "vue-elm-dist",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.15.3"
  }
}

完成以上操做,咱們要上傳的文件項目大概長這樣
新建一個文件夾如elm,把整個項目經過ftp上傳到根目錄www文件夾下github

啓動服務

登錄到你的服務端,cd到elm文件夾,執行npm install 安裝依賴,而後pm2 start app.js就成功啓動服務了
如今經過ip加端口形式能正常訪問,可是若是想經過域名訪問就須要配置nginx映射express

nginx 端口映射配置

首先你須要把一個二級域名解析到你的主機ip,好比我使用的elm.86886.wang這個二級域名
配置文件和以前的基本一致npm

upstream elm {
    server 127.0.0.1:8082;
}

server {
    listen 80;
    server_name elm.86886.wang;

    location / {
        proxy_set_header Host  $http_host;
        proxy_set_header X-Real-IP  $remote_addr;  
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Nginx-proxy true;
        proxy_pass http://elm;
        proxy_redirect off;
    }
}

我把它命名爲elm-8082.conf
而後經過ftp上傳到/etc/nginx/conf.d/目錄下
執行sudo nginx -s reload重啓nginx服務器,過個十分鐘就應該能正常訪問了 點擊訪問json

相關文章
相關標籤/搜索