vue、react等单页面项目应该这样子部署到服务器


Posted in Javascript onJanuary 03, 2018

最近好多伙伴说,我用vue做的项目本地是可以的,但部署到服务器遇到好多问题:资源找不到,直接访问index.html页面空白,刷新当前路由404。。。现在我们一起讨论下单页面如何部署到服务器?

由于前端路由缘故,单页面应用应该放到nginx或者apache、tomcat等web代理服务器中,千万不要直接访问index.html,同时要根据自己服务器的项目路径更改react或vue的路由地址。

如果说项目是直接跟在域名后面的,比如:http://www.sosout.com ,根路由就是 '/'。

如果说项目是直接跟在域名后面的一个子目录中的,比如:http://www.sosout.com/children ,根路由就是 '/children ',不能直接访问index.html。

以配置Nginx为例,配置过程大致如下:(假设:

1、项目文件目录: /mnt/html/spa(spa目录下的文件就是执行了npm run dist 后生成的dist目录下的文件)

2、访问域名:spa.sosout.com)

进入nginx.conf新增如下配置:

server {
  listen 80;
  server_name spa.sosout.com;
  root /mnt/html/spa;
  index index.html;
  location ~ ^/favicon\.ico$ {
    root /mnt/html/spa;
  }

  location / {
    try_files $uri $uri/ /index.html;
    proxy_set_header  Host       $host;
    proxy_set_header  X-Real-IP    $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  X-Forwarded-Proto $scheme;
  }
  access_log /mnt/logs/nginx/access.log main;
}

注意事项:

1、配置域名的话,需要80端口,成功后,只要访问域名即可访问的项目

2、如果你使用了react-router的 browserHistory 模式或 vue-router的 history 模式,在nginx配置还需要重写路由:

server {
  listen 80;
  server_name spa.sosout.com;
  root /mnt/html/spa;
  index index.html;
  location ~ ^/favicon\.ico$ {
    root /mnt/html/spa;
  }

  location / {
    try_files $uri $uri/ @fallback;
    index index.html;
    proxy_set_header  Host       $host;
    proxy_set_header  X-Real-IP    $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  X-Forwarded-Proto $scheme;
  }
  location @fallback {
    rewrite ^.*$ /index.html break;
  }
  access_log /mnt/logs/nginx/access.log main;
}

为什么要重写路由?因为我们的项目只有一个根入口,当输入类似/home的url时,如果找不到对应的页面,nginx会尝试加载index.html,这是通过react-router就能正确的匹配我们输入的/home路由,从而显示正确的home页面,如果browserHistory模式或history模式的项目没有配置上述内容,会出现404的情况。

简单举两个例子,一个vue项目一个react项目:

vue项目:

域名:http://tb.sosout.com

vue、react等单页面项目应该这样子部署到服务器

import App from '../App'
// 首页
const home = r => require.ensure([], () => r(require('../page/home/index')), 'home')
// 物流
const logistics = r => require.ensure([], () => r(require('../page/logistics/index')), 'logistics')
// 购物车
const cart = r => require.ensure([], () => r(require('../page/cart/index')), 'cart')
// 我的
const profile = r => require.ensure([], () => r(require('../page/profile/index')), 'profile')
// 登录界面
const login = r => require.ensure([], () => r(require('../page/user/login')), 'login')
export default [{
 path: '/',
 component: App, // 顶层路由,对应index.html
 children: [{
  path: '/home', // 首页
  component: home
 }, {
  path: '/logistics', // 物流
  component: logistics,
  meta: {
   login: true
  }
 }, {
  path: '/cart', // 购物车
  component: cart,
  meta: {
   login: true
  }
 }, {
  path: '/profile', // 我的
  component: profile
 }, {
  path: '/login', // 登录界面
  component: login
 }, {
  path: '*',
  redirect: '/home'
 }]
}]

vue、react等单页面项目应该这样子部署到服务器

############
# 其他配置
############

http {
  ############
  # 其他配置
  ############
  server {
    listen 80;
    server_name tb.sosout.com;
    root /mnt/html/tb;
    index index.html;
    location ~ ^/favicon\.ico$ {
      root /mnt/html/tb;
    }
  
    location / {
      try_files $uri $uri/ @fallback;
      index index.html;
      proxy_set_header  Host       $host;
      proxy_set_header  X-Real-IP    $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header  X-Forwarded-Proto $scheme;
    }
    location @fallback {
      rewrite ^.*$ /index.html break;
    }
    access_log /mnt/logs/nginx/access.log main;
  }
  ############
  # 其他配置
  ############  
}

react项目:

域名:http://antd.sosout.com

vue、react等单页面项目应该这样子部署到服务器

/**
* 疑惑一:
* React createClass 和 extends React.Component 有什么区别?
* 之前写法:
* let app = React.createClass({
*   getInitialState: function(){
*    // some thing
*   }
* })
* ES6写法(通过es6类的继承实现时state的初始化要在constructor中声明):
* class exampleComponent extends React.Component {
*  constructor(props) {
*    super(props);
*    this.state = {example: 'example'}
*  }
* }
*/

import React, {Component, PropTypes} from 'react'; // react核心
import { Router, Route, Redirect, IndexRoute, browserHistory, hashHistory } from 'react-router'; // 创建route所需
import Config from '../config/index';
import layout from '../component/layout/layout'; // 布局界面

import login from '../containers/login/login'; // 登录界面

/**
 * (路由根目录组件,显示当前符合条件的组件)
 * 
 * @class Roots
 * @extends {Component}
 */
class Roots extends Component {
  render() {
    // 这个组件是一个包裹组件,所有的路由跳转的页面都会以this.props.children的形式加载到本组件下
    return (
      <div>{this.props.children}</div>
    );
  }
}

// const history = process.env.NODE_ENV !== 'production' ? browserHistory : hashHistory;

// 快速入门
const home = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/home/homeIndex').default)
  }, 'home');
}

// 百度图表-折线图
const chartLine = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/charts/lines').default)
  }, 'chartLine');
}

// 基础组件-按钮
const button = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/general/buttonIndex').default)
  }, 'button');
}

// 基础组件-图标
const icon = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/general/iconIndex').default)
  }, 'icon');
}

// 用户管理
const user = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/user/userIndex').default)
  }, 'user');
}

// 系统设置
const setting = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/setting/settingIndex').default)
  }, 'setting');
}

// 广告管理
const adver = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/adver/adverIndex').default)
  }, 'adver');
}

// 组件一
const oneui = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/ui/oneIndex').default)
  }, 'oneui');
}

// 组件二
const twoui = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../containers/ui/twoIndex').default)
  }, 'twoui');
}

// 登录验证
const requireAuth = (nextState, replace) => {
  let token = (new Date()).getTime() - Config.localItem('USER_AUTHORIZATION');
  if(token > 7200000) { // 模拟Token保存2个小时
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    });
  }
}

const RouteConfig = (
  <Router history={browserHistory}>
    <Route path="/home" component={layout} onEnter={requireAuth}>
      <IndexRoute getComponent={home} onEnter={requireAuth} /> // 默认加载的组件,比如访问www.test.com,会自动跳转到www.test.com/home
      <Route path="/home" getComponent={home} onEnter={requireAuth} />
      <Route path="/chart/line" getComponent={chartLine} onEnter={requireAuth} />
      <Route path="/general/button" getComponent={button} onEnter={requireAuth} />
      <Route path="/general/icon" getComponent={icon} onEnter={requireAuth} />
      <Route path="/user" getComponent={user} onEnter={requireAuth} />
      <Route path="/setting" getComponent={setting} onEnter={requireAuth} />
      <Route path="/adver" getComponent={adver} onEnter={requireAuth} />
      <Route path="/ui/oneui" getComponent={oneui} onEnter={requireAuth} />
      <Route path="/ui/twoui" getComponent={twoui} onEnter={requireAuth} />
    </Route>
    <Route path="/login" component={Roots}> // 所有的访问,都跳转到Roots
      <IndexRoute component={login} /> // 默认加载的组件,比如访问www.test.com,会自动跳转到www.test.com/home
    </Route>
    <Redirect from="*" to="/home" />
  </Router>
);

export default RouteConfig;

vue、react等单页面项目应该这样子部署到服务器

############
# 其他配置
############

http {
  ############
  # 其他配置
  ############
  server {
    listen 80;
    server_name antd.sosout.com;
    root /mnt/html/reactAntd;
    index index.html;
    location ~ ^/favicon\.ico$ {
      root /mnt/html/reactAntd;
    }

    location / {
      try_files $uri $uri/ @router;
      index index.html;
      proxy_set_header  Host       $host;
      proxy_set_header  X-Real-IP    $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header  X-Forwarded-Proto $scheme;
    }
    location @router {
      rewrite ^.*$ /index.html break;
    }
    access_log /mnt/logs/nginx/access.log main;
  }

  ############
  # 其他配置
  ############  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
json原理分析及实例介绍
Nov 29 Javascript
jquery利用命名空间移除绑定事件的方法
Mar 11 Javascript
javascript for-in有序遍历json数据并探讨各个浏览器差异
Nov 30 Javascript
轮播图组件js代码
Aug 08 Javascript
jQuery时间日期三级联动(推荐)
Nov 27 Javascript
Bootstrap Table使用整理(五)之分页组合查询
Jun 09 Javascript
利用JS动态生成隔行换色HTML表格的两种方法
Oct 09 Javascript
vue 实现强制类型转换 数字类型转为字符串
Nov 07 Javascript
Javascript异步执行不按顺序解决方案
Apr 30 Javascript
Vue.js暴露方法给WebView的使用操作
Sep 07 Javascript
利用js实现简易红绿灯
Oct 15 Javascript
解决ant design vue 表格a-table二次封装,slots渲染的问题
Oct 28 Javascript
AngularJS实现的2048小游戏功能【附源码下载】
Jan 03 #Javascript
浅谈node模块与npm包管理工具
Jan 03 #Javascript
JavaScript基于面向对象实现的猜拳游戏
Jan 03 #Javascript
JS实现的简单拖拽购物车功能示例【附源码下载】
Jan 03 #Javascript
基于js 各种排序方法和sort方法的区别(详解)
Jan 03 #Javascript
vue项目中用cdn优化的方法
Jan 03 #Javascript
不到200行 JavaScript 代码实现富文本编辑器的方法
Jan 03 #Javascript
You might like
PHP 5.3.0 安装分析心得
2009/08/07 PHP
yii2中LinkPager增加总页数和总记录数的实例
2017/08/28 PHP
PHP的PDO大对象(LOBs)
2019/01/27 PHP
gearman中任务的优先级和返回状态实例分析
2020/02/27 PHP
自适应图片大小的弹出窗口
2006/07/27 Javascript
随机显示经典句子或诗歌的javascript脚本
2007/08/04 Javascript
js的.innerHTML = &quot;&quot;IE9下显示有错误的解决方法
2013/09/16 Javascript
jquery-syntax动态语法着色示例代码
2014/05/14 Javascript
下拉框select的绑定示例
2014/09/04 Javascript
node.js中的fs.symlink方法使用说明
2014/12/15 Javascript
详解javascript高级定时器
2015/12/31 Javascript
jQuery实现控制文字内容溢出用省略号(…)表示的方法
2016/02/26 Javascript
jQuery异步提交表单的两种方式
2016/09/13 Javascript
原生js实现倒计时--2018
2017/02/21 Javascript
jQuery 改变P标签文本值方法
2018/02/24 jQuery
css配合JavaScript实现tab标签切换效果
2018/10/11 Javascript
详解小程序不同页面之间通讯的解决方案
2018/11/23 Javascript
在vue中使用echars实现上浮与下钻效果
2019/11/08 Javascript
简单了解JavaScript弹窗实现代码
2020/05/07 Javascript
解决idea开发遇到javascript动态添加html元素时中文乱码的问题
2020/09/29 Javascript
详解基于element的区间选择组件校验(交易金额)
2021/01/07 Javascript
在Linux上安装Python的Flask框架和创建第一个app实例的教程
2015/03/30 Python
详解Python中DOM方法的动态性
2015/04/11 Python
python排序方法实例分析
2015/04/30 Python
pandas通过索引进行排序的示例
2018/11/16 Python
pytorch神经网络之卷积层与全连接层参数的设置方法
2019/08/18 Python
python小程序基于Jupyter实现天气查询的方法
2020/03/27 Python
Jupyter notebook 启动闪退问题的解决
2020/04/13 Python
爱尔兰灯和灯具网上商店:Lights.ie
2018/03/26 全球购物
Huda Beauty官方商店:化妆和美容产品
2020/09/05 全球购物
数据库的约束含义
2012/09/09 面试题
领导干部培训感言
2014/01/23 职场文书
教师个人自我剖析材料
2014/09/29 职场文书
房屋过户委托书范本
2014/10/07 职场文书
2014年评职称工作总结
2014/11/20 职场文书
聚会通知怎么写
2015/04/23 职场文书