vue项目http代理,axios

  • vue-cli3.0以后,创建的服务器的配置文件被隐藏了,需要对服务器进行配置的话,必须在项目根目录下手动添加一个vue.config.js文件进行配置,vue在启动项目的时候,会把这个配置项整合到项目中。
  • 对于前后端分离的项目,前端需要使用ajax请求从服务器请求数据,所以就必须对vue项目提供的http服务器设置代理,将ajax请求代理目标服务器。

安装

npm install axios

导入

main.js
将axios添加到vue构造函数的原型上,这样所有的组件都可以访问原型中的axios

import axios from "axios";
Vue.prototype.http = axios;

axios对象的 get请求

// axios对象的.get方法,用于发起一个get请求,第一个参数是请求地址,第二个参数是本次请求的配置对象,其中params选项是get请求的参数。
            // get方法返回一个promise,所以可以使用.then .catch
            axios.get("/api/get",{
                params:{
                    name:"笑笑",
                    age:13
                }
            })
            .then(res=>{
                // 请求成功的回调函数中参数不是响应数据,而是整个响应报文,其中data才是响应数据。
                console.log(res.data);
                this.msg = res.data.msg
            })
            .catch(function(err){
                console.log(err);
            });

axios对象的post请求

 let data = {name:"sun",age:30};
            // data = this.urlcode.encode(data);
            
            // axios发起post请求,第二个参数可以是urlencode格式的字符串,这样发起的请求数据格式是urlencode格式,也可以是一个对象,这样发起的请求数据格式是JSON。
            this.http.post("/api/post",data)
            .then(res=>{
                this.postMsg = res.data.msg;
				
            })

待续…

猜你喜欢

转载自blog.csdn.net/WXB_gege/article/details/105774701