Apache虛擬目錄配置及vue-cli反向代理

配置需求來自於前後端分離。後臺由於使用php或者java,但是前端使用vue,react這些框架時怎麼和後端有效的數據通信。反向代理是個很好的選擇,雖然jsonp也可以,單並不好玩。

Apache配置虛擬目錄 
-實際上線項目需要通過域名來訪問,比如http://www.xxx.com,但在本機上如何配置虛擬域名來訪問本機的項目呢?

1.找到C:\Windows\System32\drivers\etc\hosts這個文件添加以下格式內容

127.0.0.1       www.mytest.com //你的虛擬域名
  • 1

2.配置Apache項目目錄 
1.找到 \apache\conf\httpd.conf 這個文件,修改內容

# Virtual hosts
Include conf/extra/httpd-vhosts.conf (這行的註釋#去掉)
  • 1
  • 2

2.找到\apache\conf\extra\httpd-vhosts.conf這個文件配置項目目錄

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/mobileApp" ##你的後端項目目錄
    ServerName www.mytest.com ##虛擬域名
    ##ServerAlias www.dummy-host.example.com
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
    <Directory "C:/xampp/htdocs/mobileApp"> 
        Options Indexes FollowSymLinks
        DirectoryIndex index.html index.php
        AllowOverride all
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

3.proxyTable代理配置,以vue-cli爲例

   proxyTable: {
      '/api': {
        target: 'http://www.mytest.com/api',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

這樣就可以實現跨域訪問了。 
示例:

   $.ajax({
                url: '/api/indexList.php',
                type: 'GET',
                success: function (data) {
                    that.list = data.data;
                    console.log(data);
                }
            })
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章