web前後端分離開發——前端Vue

前後分離開發主要是通過前後端接口來進行傳數據,因此就要配置跨域訪問。對於新手來說,跨域設置可能是個讓人頭痛的問題。

因此,我這裏主要貼一下前端vue項目及服務器端的跨域配置。

vue項目跨域配置:

config>index.js>proxyTable:

proxyTable: {
      '/api': { 
        target:'http://10x.xx.xx.x1', // api服務器的ip地址或域名   
        changeOrigin:true, // 允許跨域請求
        pathRewrite:{
            '^/api': ''
        }
      },
      '/github': {
        target: 'http://10x.xx.xx.x1', // api服務器的ip地址或域名   
        changeOrigin: true,
        pathRewrite: {
            '^/github': ''
        }
      },
      '/scnuapi': {        
        target: 'http://10x.xx.xx.x1', // api服務器的ip地址或域名   
        changeOrigin: true,
        pathRewrite: {
            '^/scnuapi': ''
        }
      },
      '/reboot': {        
        target: 'http://10x.xx.xx.x1', // api服務器的ip地址或域名   
        changeOrigin: true,
        pathRewrite: {
            '^/reboot': ''
        }
      },
      
    },

注意這個配置後,要重新編譯項目,不會自動編譯生效的!!!

服務器端 nginx

vue項目打包後放到nginx項目html中

設置nginx>conf>nginx.conf  : http{    server{  (定位)

listen       80;  // nginx服務器監聽的端口
        server_name localhost 127.0.0.1(服務器ip);
		
		client_max_body_size 2G;#解決上傳文件過大
        charset utf-8;

        #access_log  logs/host.access.log  main;
        location / {
			root   html;
			index  index.html index.htm;
            add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';
        }
		location /api {
			#修正uri
			rewrite ^/api/(.*) /$1 break;
			#後端服務地址
			proxy_pass  http://10x.xx.xx.xx;// 服務器ip
			add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';	 
		}
		location /github {
			#修正uri
			rewrite ^/github/(.*) /$1 break;
			#後端服務地址
			proxy_pass  https://github.com;
			add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';	 
		}
		location /scnuapi {
			#修正uri
			rewrite ^/scnuapi/(.*) /$1 break;
			#後端服務地址
			proxy_pass  http://10x.xx.xx.xx;// 服務器ip
			add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';	 
		}
		location /reboot {
			#修正uri
			rewrite ^/reboot/(.*) /$1 break;
			#後端服務地址
			proxy_pass  http://openapi.tuling123.com;
			add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';	 
		}

注意配置這個後一定要重啓nginx, 因爲nginx沒有明顯的重啓按鈕,所以如果不行,試着關機試試,哈哈哈哈~~~~

以上就是前後端分離的前端部署,如果還不清楚,可以下載下面的文件仔細看看。

 

 

web前後端分離開發——前端Vue

這個前端項目跟下面這個後端java是配套的

web前後端分離開發——後端SpringMVC java開發

裏面有個圖靈機器人沒有刪,各位不要亂掉我的圖靈機器人接口,否則我會刪資源的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章