vue-axios数据请求

src/main.js中的配置

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' //设置请求头部
axios.defaults.baseURL = 'http://127.0.0.1:8081/news/'  //所请求的连接
axios.defaults.withCredentials = true  //跨域
Vue.prototype.$http = axios
Vue.prototype.$axios = axios
Vue.prototype.$qs = qs

config/index.js的设置

proxyTable: {
        '/api' : {
          // 测试环境
          target: 'http://127.0.0.1:8081/',
          changeOrigin: true,
          pathRewrite: {
            '^/api': ''
          }
        }
    },

在vue中请求

this.$axios
              .post('/newType', this.$qs.stringify(this.ruleForm), {headers: {'Content-Type': "application/x-www-form-urlencoded"}})
              .then(response => {
                withCredentials: true   //跨域请求头携带cookie
                if(response.data.code == 200){
                  this.$message({showClose: true, message: '添加成功!', type: 'success'});
                  return true;
                } else{
                  this.$message({showClose: true, message: '添加失败!', type: 'error'});
                  return false;
                }
              })
              .catch(error => {
                console.log(error)
              })

在这次请求中,this.ruleForm是发送的数据,通过this.$qs.stringify将对象序列化,转为ajax的form data 即以&连接的形式,设置头部,否则接收数据发送数据失败,这次请求,实际请求的连接是 127.0.0.1:8081/news/newsType

返回的数据是  response.data

 

另外,在创建vue时,需要在router/index 中使用import引入,并且要在

{
  path: '/',
  component: TheLayout,
  menu: true,
  name: '新闻类别管理',
  icon: 'el-icon-edit-outline',
  children: [
    {
      path: '/forms/addtype',
      name: '新闻类别添加',
      component: FuncAddType
    }, {
      path: '/forms/modtype',
      name: '新闻类别维护',
      component: FuncModType
    },
  ]
},

 

写好自己的路由

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值