vue와 같은 단일 페이지 프로젝트를 배포하고 서버에 반응하는 방법

小云云
풀어 주다: 2018-01-03 14:52:38
원래의
3387명이 탐색했습니다.

Vue로 만든 프로젝트는 로컬에서 빌드할 수 있지만 서버에 배포할 때 많은 문제가 있습니다: 리소스를 찾을 수 없습니다, index.html 페이지에 대한 직접 액세스가 비어 있습니다, 현재 경로 404를 새로 고칩니다. 이 기사에서는 주로 vue 및 React와 같은 단일 페이지 프로젝트를 서버에 배포하는 방법을 공유합니다. 资源找不到直接访问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的情况。

프론트엔드 라우팅으로 인해 단일 페이지 애플리케이션은 nginx나 apache, tomcat 등의 웹 프록시 서버에 배치해야 합니다. index.html에 직접 액세스하지 말고, React 또는 vue의 라우팅 주소를 다음에 따라 변경하세요. 자신의 서버의 프로젝트 경로.

프로젝트가 http://www.sosout.com과 같이 도메인 이름을 직접 따르는 경우 루트 경로는 '/'입니다. 프로젝트가 http://www.sosout.com/children과 같이 도메인 이름 바로 뒤에 있는 하위 디렉터리에 있는 경우 루트 경로는 '/children'이며 index.html에 직접 액세스할 수 없습니다.

Nginx 구성을 예로 들면 구성 프로세스는 대략 다음과 같습니다. (가정:

1. 프로젝트 파일 디렉터리:

/mnt/html/spa (spa 디렉터리의 파일은 이후 생성된 dist 디렉터리의 파일입니다.) npm run dist가 실행됩니다) )vue와 같은 단일 페이지 프로젝트를 배포하고 서버에 반응하는 방법2. 도메인 이름에 액세스합니다: spa.sosout.com

)

nginx.conf를 입력하고 다음 구성을 추가합니다:

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와 같은 단일 페이지 프로젝트를 배포하고 서버에 반응하는 방법참고: 1. 도메인 이름, 포트 80이 필요합니다. 성공 후에는 도메인 이름에 액세스하여 액세스할 수 있는 프로젝트만

2. 반응 라우터의 browserHistory 모드 또는 vue-router의 기록 모드를 사용하는 경우 , nginx 구성에서 경로를 다시 작성해야 합니다:

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

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;
    }
    ############
    # 其他配置
    ############   
}
로그인 후 복사
라우팅을 다시 작성하는 이유는 무엇입니까? 우리 프로젝트에는 루트 항목이 하나만 있기 때문에 /home과 유사한 URL을 입력할 때 해당 페이지를 찾을 수 없으면 nginx는 index.html을 로드하려고 시도하며 이는 반응 라우터를 통해 입력과 정확하게 일치할 수 있습니다. home 경로를 사용하여 올바른 홈 페이지를 표시합니다. browserHistory 모드 또는 기록 모드 프로젝트가 위 콘텐츠를 구성하지 않으면 404가 발생합니다. Vue 프로젝트 하나와 React 프로젝트 하나, 두 가지 예를 들어보세요.

vue 프로젝트: vue와 같은 단일 페이지 프로젝트를 배포하고 서버에 반응하는 방법도메인 이름: http://tb.sosout.com

vue와 같은 단일 페이지 프로젝트를 배포하고 서버에 반응하는 방법

/**
* 疑惑一:
* 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;
로그인 후 복사


react 프로젝트:

도메인 이름: http://antd.sosout.com

rrreee

🎜🎜🎜rrreee🎜관련 추천: 🎜🎜🎜 🎜Docker 배포 PHP를 사용하는 방법 개발 환경🎜 🎜🎜🎜git 배포의 PHP 구현 설명🎜🎜🎜🎜템플릿 엔진 기반 PHP 디자인 패턴 컨테이너 배포 프레임워크🎜🎜🎜🎜🎜

위 내용은 vue와 같은 단일 페이지 프로젝트를 배포하고 서버에 반응하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!