vue与后台交互之post用法
vue解决跨域
-
安装
axios
cnpm install axios --save
-
在
config/index.js
proxyTable: { '/api': { //使用"/api"来代替"http://f.apiplus.c" target: 'http://127.0.0.1:8000/', //源地址 changeOrigin: true, //改变源 pathRewrite: { '^/api': '' //路径重写 } } },
-
在
src/main.js
import axios from 'axios' Vue.prototype.axios = axios
-
在
src/components
下新建文件User.vue
<template> <div> <h2>用户注册</h2> username: <input type='text' v-model='username'> password: <input type='password' v-model='password'> <button @click='register'> 注册 </button> </div> </template> <script> export default{ name:'user', data(){ return { username:'', password:'' } }, methods:{ register:function(){ var params = new URLSearchParams(); params.append('name',this.username); params.append('password',this.password); this.axios({ method:'post', // api 是 http://127.0.0.1:8000 的简写 url:'api/app01/add/', data:params }).then(res=>{ console.log(res); }).catch(error=>{ console.log(error); }) } } } </script>
-
在
router/index.js
下import user from '@/components/User.vue' export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld }, { path:'/user/register', name:'user', component:user } ] })