在nginx服务器部署vue项目

1.加入.env.dev和.env.prod环境信息
在这里插入图片描述
.env.dev
变量必须以VUE_APP开头,例如VUE_APP_URL,这样可以通过process.env.VUE_APP_URL访问到。

NODE_ENV = 'development'
VUE_APP_URL='http://localhost:8080'

.env.prod

NODE_ENV = 'production'
VUE_APP_URL='http://39.101.xxx.xxx'//服务器ip

2.request.js加入

import axios from 'axios'
import vue from 'vue'

const request= function (query) {
  return axios.request(query)
  .then( res =>{
    return Promise.resolve(res.data)
  })
  .catch(err=> {
    return Promise.reject(err)
  })
}

const post=function (url,params){
  const query={
    baseURL: process.env.VUE_APP_URL,//访问当前环境的URL
    url: url,
    method: 'post',
    withCredentials:true,
    timeout: 50000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true }
  }
  return request(query)
}

const get = function(url,params) {
  const query={
    baseURL: process.env.VUE_APP_URL,
    url: url,
    method: 'get',
    withCredentials : true,
    timeout: 50000,
    params: params,
    headers: { 'request-ajax': true }
  }
  return request(query);
}


export{
  post,
  get,
}

3.在package.json中加入生产环境打包配置:

 "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
	"build:dev": "vue-cli-service build --mode dev",
	"build:prod": "vue-cli-service build --mode prod",
    "lint": "vue-cli-service lint"
  },

注意:上面的build --mode dev中的dev是和.env.dev中的dev对应的,此时若要打包上线,控制台执行: yarn build:prod 即可
4.在nginx中配置反向代理:
先看vue.config.js中devServer配置:

devServer: {
    port: 8080,
    proxy: {
      '/api': {
        target: 'http://114.55.xx.xxx:8080/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/Jhsd'
        }
      }
    }
  },

可以看到,在开发环境中api被代理到了http://114.55.xx.xxx:8080/,即接口服务器的ip地址
打开nginx中conf.d->default.conf:

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
    
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    # 配置反向代理
    location /api {
			proxy_pass http://114.55.xx.xxx:8080/Jhsd;
			add_header Access-Control-Allow-Origin *;   #表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求
		}
   
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

注意:proxy_pass http://114.55.xx.xxx:8080/Jhsd和devServer中的target: 'http://114.55.xx.xxx:8080/'代理信息保持一致

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值