首页 web前端 js教程 vue、react等单页面项目部署到服务器方法

vue、react等单页面项目部署到服务器方法

Jan 03, 2018 pm 02:52 PM
react 服务器 部署

用vue做的项目本地是可以的,但部署到服务器遇到好多问题:资源找不到直接访问index.html页面空白刷新当前路由404。本文我们主要和大家分享vue、react等单页面项目部署到服务器方法,希望能帮助到大家。

由于前端路由缘故,单页面应用应该放到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 (
            <p>{this.props.children}</p>
        );
    }
}

// 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;
    }

    ############
    # 其他配置
    ############   
}
登录后复制

相关推荐:

如何使用Docker部署PHP开发环境

实例讲解PHP实现git部署

PHP设计模式之基于模板引擎的容器部署框架


以上是vue、react等单页面项目部署到服务器方法的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何将Dnsmasq配置为DHCP中继服务器 如何将Dnsmasq配置为DHCP中继服务器 Mar 21, 2024 am 08:50 AM

DHCP中继的作用是将接收到的DHCP数据包转发到网络上的另一个DHCP服务器,即使这两个服务器位于不同的子网中。通过使用DHCP中继,您可以实现在网络中心部署一个集中式的DHCP服务器,并利用它为所有网络子网/VLAN动态分配IP地址。Dnsmasq是一种常用的DNS和DHCP协议服务器,可以配置为DHCP中继服务器,以帮助管理网络中的动态主机配置。在本文中,我们将向您展示如何将dnsmasq配置为DHCP中继服务器。内容主题:网络拓扑在DHCP中继上配置静态IP地址集中式DHCP服务器上的D

用PHP构建IP代理服务器的最佳实践指南 用PHP构建IP代理服务器的最佳实践指南 Mar 11, 2024 am 08:36 AM

在网络数据传输中,IP代理服务器扮演着重要的角色,能够帮助用户隐藏真实IP地址,保护隐私、提升访问速度等。在本篇文章中,将介绍如何用PHP构建IP代理服务器的最佳实践指南,并提供具体的代码示例。什么是IP代理服务器?IP代理服务器是一种位于用户与目标服务器之间的中间服务器,它充当用户与目标服务器之间的中转站,将用户的请求和响应进行转发。通过使用IP代理服务器

epic服务器离线进不了游戏怎么办?epic离线进不了游戏解决方法 epic服务器离线进不了游戏怎么办?epic离线进不了游戏解决方法 Mar 13, 2024 pm 04:40 PM

  epic服务器离线进不了游戏怎么办?这个问题想必很多小伙伴都有遇到过,出现了此提示就是导致正版的游戏无法启动,那么出现这个问题一般是网络和安全软件干扰导致的,那么应该怎么解决呢,本期小编就来和大伙分享解决方法,希望今日的软件教程可以帮助各位解决问题。  epic服务器离线进不了游戏怎么办:  1、很可能是被安全软件干扰了,将游戏平台和安全软件关闭在重启。  2、其次就是网络波动过大,尝试重启一次路由器,看看是否有效,如果条件可以的话,可以尝试使用5g移动网络来进行操作。  3、然后有可能是更

Yolov10:详解、部署、应用一站式齐全! Yolov10:详解、部署、应用一站式齐全! Jun 07, 2024 pm 12:05 PM

一、前言在过去的几年里,YOLOs由于其在计算成本和检测性能之间的有效平衡,已成为实时目标检测领域的主导范式。研究人员探索了YOLO的架构设计、优化目标、数据扩充策略等,取得了显着进展。同时,依赖非极大值抑制(NMS)进行后处理阻碍了YOLO的端到端部署,并对推理延迟产生不利影响。在YOLOs中,各种组件的设计缺乏全面彻底的检查,导致显着的计算冗余,限制了模型的能力。它提供了次优的效率,以及相对大的性能改进潜力。在这项工作中,目标是从后处理和模型架构两个方面进一步提高YOLO的性能效率边界。为此

PHP、Vue和React:如何选择最适合的前端框架? PHP、Vue和React:如何选择最适合的前端框架? Mar 15, 2024 pm 05:48 PM

PHP、Vue和React:如何选择最适合的前端框架?随着互联网技术的不断发展,前端框架在Web开发中起着至关重要的作用。PHP、Vue和React作为三种具有代表性的前端框架,每一种都具有其独特的特点和优势。在选择使用哪种前端框架时,开发人员需要根据项目需求、团队技能和个人偏好做出明智的决策。本文将通过比较PHP、Vue和React这三种前端框架的特点和使

Java框架与前端React框架的整合 Java框架与前端React框架的整合 Jun 01, 2024 pm 03:16 PM

Java框架与React框架的整合:步骤:设置后端Java框架。创建项目结构。配置构建工具。创建React应用。编写RESTAPI端点。配置通信机制。实战案例(SpringBoot+React):Java代码:定义RESTfulAPI控制器。React代码:获取并显示API返回的数据。

如何在服务器上安装 PHP FFmpeg 扩展? 如何在服务器上安装 PHP FFmpeg 扩展? Mar 28, 2024 pm 02:39 PM

如何在服务器上安装PHPFFmpeg扩展?在服务器上安装PHPFFmpeg扩展可以帮助我们在PHP项目中处理音视频文件,实现音视频文件的编解码、剪辑、处理等功能。本文将介绍如何在服务器上安装PHPFFmpeg扩展,以及具体的代码示例。首先,我们需要确保服务器上已经安装了PHP以及FFmpeg。如果没有安装FFmpeg,可以按照以下步骤安装FFmpe

Golang 服务器的优势及效用详解 Golang 服务器的优势及效用详解 Mar 20, 2024 pm 01:51 PM

Golang是一种由Google开发的开源编程语言,它具有高效、快速、强大的特点,被广泛应用在云计算、网络编程、大数据处理等领域。作为一种强类型、静态语言,Golang在构建服务器端应用程序时具有诸多优势。本文将详细解析Golang服务器的优势及效用,并通过具体的代码示例来说明其强大之处。1.高性能Golang的编译器能够将代码编译成为本地代

See all articles