vue3 HTTP请求

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue3 HTTP请求

sharryling   2022-06-28 我要评论

vue3-HTTP请求

jsonp原理 结合node.js

服务端:

第15行,相当于在前端返回了js代码,调用show()

第19行相当于 20-22行代码

show被写死了,最好的方式,客户端把自己的函数名传过去!如下:

传参方法:

Get Post请求

1.导入包: vue-resourse

2.调用get: this.$http.get(‘url参数’).then((() => { 回调函数 }

3.调用post

设置根域名

emulateJSON:true

如果不带上面的参数,就会出问题!!

所以也可以设置全局

vue3-HTTP请求发出后,判断哪里出问题了

在请求后添加

.catch(function (error) {
    if (error.response) {
      // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
      console.log("请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围");
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 请求已经成功发起,但没有收到响应
      // `error.request` 在浏览器中是 XMLHttpRequest 的实例,
      // 而在node.js中是 http.ClientRequest 的实例
      console.log("请求已经成功发起,但没有收到响应");
      console.log(error.request);
    } else {
      // 发送请求时出了点问题
      console.log("发送请求时出了点问题");
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

然后根据控制台,返回的信息判断。

控制台:结果页面 -> 按F12 -> 点击控制台

例如:

    service.get('/trace/'+sourceSearchInput.value).then(res => {
      dialogSearchResult.value.push(res);   //返回对象,push进去 & vue3中 取变量值-》变量.value
      //console.log(res);
    }).catch(function (error) {
    if (error.response) {
      // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
      console.log("请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围");
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 请求已经成功发起,但没有收到响应
      // `error.request` 在浏览器中是 XMLHttpRequest 的实例,
      // 而在node.js中是 http.ClientRequest 的实例
      console.log("请求已经成功发起,但没有收到响应");
      console.log(error.request);
    } else {
      // 发送请求时出了点问题
      console.log("发送请求时出了点问题");
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们