18910140161

Vue简单封装axios解决post请求后端无法接收参数的问题

顺晟科技

2021-08-28 09:38:22

92

1.在src/下创建新的API文件夹、api/下创建新的index.js和public.js

在Public.js中:

1 import axios from ' axios

2 import QS from 'qs '

3 import router from./router

4 import { messagebox } from ' mint-ui '

5

6 //注意事项,请写如下

7 var instance=axios . create();

8 instance . defaults . time out=10000;

9 instance . defaults . headers . post[' content-type ']=' application/x-www-form-urlence

10

11 export default {

12 fetchGet(url,params={}) {

13 return new promise ((resolve,reject)={

14axios.get (URL,params)。then (RES={

15 IF(RES . data . code===302){

16 MessageBox(“提示”,“登录失败,请重新登录”);

17 MessageBox.alert(“登录失败”)。“重新登录”,“提示”)。then(action={

18 router . push('/log in ');

19 });

20}

21 resolve(RES . data);

22 })。catch(error={

23 reject(error);

(24})

(25})

26 .

27 fetchPost(url,params={}) {

28 /*

29 axios post请求后端无法接收参数问题:

30

31解决方案1:有效,但兼容性不好。并非所有浏览器都支持

32 let data=new URLSearchParams()

33 for (var key in params) {

34data.append(键,params [键])

35}

36 */

37

38 //解决方案2:使用QS模块(包含在axios中)并使用qs.stringify()序列化params

39 return new promise ((resolve,reject)={

40axios.post (URL,qs.stringify (params))。then (RES={

41 resolve(RES . data);

42 })。catch(error={

43 reject(error);

44})

45})

46}

47}

2.在index.js中:

1导入http from。/public

2

3 exportconstgetstation=(params)={

4 return http . fetchget('/hydro/rest/getbelonguser ',params);

5}

6

7 export const userlogin=(params)={

8 return http . fetch post('/hydro/rest/log in ',params);

9}

3.Login.vue调用post请求方法3360

1 template

2 div类=' login '

3 h1登录页/h1

请输入4 input type='text' placeholder='用户名' v-model='Username '

5输入input type=' Password ' placeholder='密码' v-model='Password '

6 input type='button' value='注册表' @click='toLogin '

7 /div

8/模板

9

10脚本

11import {userlogin} from '././API/index '

12

13 export default {

14 name: ' app ',

15 data() {

16 return {

17 Username: ' ',

18 Password: ' '

19}

20}

21 methods: {

22 toLogin() {

23 let params={

24 username: this。Username,

25 password: this。Password

26 };

27

28 userLogin(params)。then(res={

29if(RES . code===200){

30 this.$ router.push ('/home ')

31}

(32})

33}

34}

35}

36/脚本

4.从Home.vue调用get请求方法

1 template

2 h1 class='home '

3 {{stationName}}

4 /h1

5/模板

6

7 script

8导入{getstation} from '././API/index '

9

10 export default {

11 data() {

12 return{

13 stationName: ' '

14}

15 .

16 created() {

17 getStation()。then(res={

18 this . station name=RES . msg;

19})

20}

21}

22/脚本

我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航