搭建Nginx + Vue +PHP的前后端开发过程

1、新建一个vue项目

2、安装axios   npm install axios

3、在main.js文件里添加
import axios from 'axios'
Vue.prototype.axios = axios
4、开发过程中必定是跨域名请求,所以在vue.config.json中
module.exports = {
    devServer: {
        proxy: {
            "/api": {
                target: 'http://www.xxx.com',
                secure: false,
                changeOrigin: true
            }
        }
    }
}
5、然后在nginx配置文件中添加域名
server {
  listen 80;
  server_name www.xxx.com;
  default_type text/html;
  charset utf-8;

  root D:/www/xxx/dist;

  location / {
    index index.html;
    try_files $uri /index.html;
  }

  location /api {
    rewrite ^/(.*) /index.php?$1 last;
  }

  location ~* \.(gif|jpg|jpeg|png|js|css|ico)$
  {
     if (!-f $request_filename) {
         return 404;
     }
  }
 
  location ~ \.php$ {
    internal;
    root D:/www/xxx/public;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }
}
6、后面就可以开始愉快的开发啦
this.axios.get('/api/test/data', {params: {id: 110}})
.then(res => {res.data})
.catch(error => {console.log(error)})
7、我用的是Yaf框架,所以在RouterPlugin里
public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response)
{
    $request_uri = explode('/', ltrim($request->getRequestUri(), '/'), 2);
    if ($request_uri[0] == 'api') {
        $request->setRequestUri('/'.$request_uri[1]);
    }
}

这样就能正确的执行原本的TestController下的dataAction方法啦。