vuejs怎么和thinkphp結合


vue在服務端部署時,我們都知道通過npm run build 指令打包好的dist文件,通過http指定是可以直接瀏覽的,Thinkphp通過域名指向index.php文件才可以瀏覽。要使前端正常調用后端數據。

有兩種方法:

1、前端跨域調用后端數據。

2、前端打包文件部署在后端的服務器文件夾下(同域)。

web服務器: apache

如:跨域

在服務器配置站點:

在路徑/home/www/  下創建test項目文件夾,用來放項目文件。

找到httpd-vhosts.conf文件配置站點

前端站點:

<VirtualHost *:80>

    ServerName test.test.com

    DocumentRoot "/home/www/test/dist" 

    DirectoryIndex index.html

</VirtualHost>

后端站點:

<VirtualHost *:80>

    ServerName test.testphp.com

    DocumentRoot "/home/www/test/php" 

    DirectoryIndex index.php

</VirtualHost>

 

   

將前端打包好的dist文件放在/home/www/test/ 文件夾下,運行http://test.test.com可瀏覽,當路徑改變時,刷新會出現404錯誤。此時dist文件下創建一個.htaccess文件,當路徑不存在時,路徑指向http://test.test.com/index.html能解決此問題。

<IfModule mod_rewrite.c>

  RewriteEngine On

  RewriteBase /

  RewriteRule ^index\.html$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f

  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteRule . /index.html [L]

</IfModule>

 

鏈接:https://pan.baidu.com/s/1v5gm7n0L7TGyejCmQrMh2g 提取碼:x2p5

免費分享,但是X度限制嚴重,如若鏈接失效點擊鏈接或搜索加群 群號518475424

在/home/www/test文件夾下創建項目根目錄php文件夾,將thinkphp文件放在php下。TP5的入口文件在public文件下,在這將public下的入口文件index.php挪到php文件夾下(個人習慣將入口文件放在項目根目錄), 后端綁定Index模塊。

前端調用后端接口,存在跨域,跨域解決方法有好幾種,在這我將在后端php做配置,解決跨域問題,在公用控制器設置跨域配置:

class Common extends Controller

{

    public $param;

    // 設置跨域訪問

    public function _initialize()

    {

        parent::_initialize();

        isset($_SERVER['HTTP_ORIGIN']) ? header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']) : '';

        header('Access-Control-Allow-Credentials: true');

        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId");

        $param =  Request::instance()->param();

        $this->param = $param;

    }

}

 

   

前端調用登錄接口: this.axios.post('http://test.testphp.com/index.php/base/login', {user: '', password: ''})。

(可在webpack.base.conf.js文件下可定義接口:http://test.testphp.com/index.php/)

同域

后端配置同上,公共配置器中的header配置注釋。將前端的dist文件下的所有文件(包含.htaccess),放在php文件夾下。將后端index控制器的index方法的路徑重定向php下的index.html文件:

namespace app\index\controller;

use think\Controller;

class Index extends Controller

{

    public function index() {

        $this->redirect('/index.html');

}

 

   

前端調用登錄接口: this.axios.post('/index.php/base/login', {user: '', password: ''})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM