基于vue-cli的反向代理设置及axios获取json数据

一、后端接口搭建

后端用的是php,自己只是个菜鸟,复习了下基础知识后搭建出来的,环境用的是phpstudy集成环境搭建的。代码如下:

<?php 
	header('content-type:application/json;charset=utf8');
	function connect_mysql(){
		
		$servername = "localhost";
		$username = "root";
		$password = "root";
		$dbname = 'test';
		 
		// 创建连接
		$conn = new mysqli($servername, $username, $password,$dbname);
		$conn->query("set character set 'utf8'");
		$conn->query("set names 'utf8'");
		// 检测连接
		if ($conn->connect_error) {
		    die("连接失败: " . $conn->connect_error);
		}	
		return $conn;		
	}
	
	function getAnswer(){
		//查询数据
	  $sql = "SELECT * FROM table_question WHERE 1";
		$con = connect_mysql();
		$result = $con->query($sql);
		
		$arr = array();
		
		if($result->num_rows > 0){
			while($row = $result->fetch_assoc()){
				array_push($arr,$row);
			}
			
		}else {
			echo '0 结果!';
		}
		$data = decodeUnicode(json_encode($arr));
		echo 	$data;		
		$con->close();		
	}
	
	function decodeUnicode($str)//解决json_encode中文乱码问题
	{
	    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
	        create_function(
	            '$matches',
	            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
	        ),
	        $str);
	}
	
	getAnswer();
	
?>


结果如下:



二、vue-cli反向代理设置

反向代理用来解决前端跨域问题,设置很简单,在vue-cli项目的config文件夹index.js文件下进行如下设置即可:


主要代码如下:

proxyTable: {
    	//本地调试
  	  '/phpserver': {		//这里是我配置的名字
		    target: 'http://localhost:90', //这个路径是我代理到本地的php服务器
		    changeOrigin: true, //开启代理
		    pathRewrite: {'^/phpserver': '/phpserver'}	//这里重写路径运行后就代理到对应地址
		  }
    },

注意:这里配置的反向代理名字:phpserver,在后端提供的接口中也应该保持一致,后端应该在php本地服务器的phpserver文件夹下进行接口开发(例如我的接口为:http://localhost:90/phpserver/answer_question),所以这里就可以根据后端提供的接口来进行设置。


三、安装axios并进行接口请求

1、打开命令行,进入vue-cli项目中,输入:cnpm install axios --save,回车进行axios安装。

2、在src的main.js中引入axios,并挂载到Vue原型链上,如下:


代码如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$http = axios;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

3、在需要获取数据的组件调用axios的方法:response响应回来的对象,它的data属性就是我们需要的数据,如下所示:


主要代码如下:

mounted:function(){
		//console.log('llllddd');
		this.$http.get('/phpserver/answer_question/index.php')
	  .then(function (response) {
	    console.log(response);
	  })
	  .catch(function (response) {
	    console.log(response);
	  });
	},


获取到的数据如下:


猜你喜欢

转载自blog.csdn.net/yemuxia_sinian/article/details/78183354