zoukankan      html  css  js  c++  java
  • VUE前端Fetch请求调用第三方接口

    Fetch官方文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

    基于Fetch请求方式,结合我的业务需求给出例子。

    1、对于get请求

    this.ipAddress是ip地址和端口,比如http://192.168.3.45:8080,产品模式下可以不需要端口,因为是默认8080的;但是开发环境下是需要端口的,有可能是我开发环境的默认端口不是8080造成的
     fetch(
            `${this.ipAddress}/api/beast/zhcx/zhcxIndex/?ipObj=${this.hostIpObj.ip}&page=${page}&size=${this.pageSize}`,
            {
              headers: {
                "Content-Type": "application/json;charset=utf-8",
              },
              method: "GET",
              mode: "cors",
            }
          )
            .then((res) =>
              res.status === 200
                ? res.json()
                : res.json().then((err) => {
                    throw err;
                  })
            )
            .then((rst) => {
              this.allItems = rst.items;
              this.total = rst.total;
            }) .catch((e) => this.$message.error(e.message));

    如果说第三方接口API也是自己写的话,下面是controller例子

    @CrossOrigin(origins = "*", maxAge = 3600)
    @RestController("beast.c.zhcx")
    @RequestMapping("/api/beast/zhcx")
    public class ZhcxsController extends KhlbsController {
        @GetMapping("/zhcxIndex")
        public Pagination<Zhcx> zhcxIndex(@RequestParam(value = "ipObj") String ip,
                                          @RequestParam(value = "page") int page,
                                          @RequestParam(value = "size") int size){}
    }

    注意@CrossOrigin(origins = "*", maxAge = 3600)这个注解很重要,要不然会出现跨域报错。

    我在开发环境下需要把application.properties的server.address=127.0.0.1改成server.address=0.0.0.0,要不然也会报错。

    如果server.address=127.0.0.1则会报错

    2、post请求

      const data = {
            headers: {
              "Content-Type": "application/json;charset=utf-8",
            },
            method: "POST",
            mode: "cors",
          };
          var body = {
            dws: this.dws,
          };
          data.body = JSON.stringify(body);
          fetch(
            `${this.ipAddress}/api/beast/zhcx/zhcx2Index/?ipObj=${this.hostIpObj.ip}`,
            data
          )
            .then((res) =>
              res.status === 200
                ? res.json()
                : res.json().then((err) => {
                    throw err;
                  })
            )
            .then((rst) => {
              this.allItems = rst;
              this.total = this.allItems.length;
    
            }) .catch((e) => this.$message.error(e.message) );
  • 相关阅读:
    python从zk获取连接并测试dubbo接口
    利用python脚本和telnet调试dubbo接口
    python制造有序中文json串的方法
    unittest用pycharm执行报错
    安装jenkins时无法解析主机:www.jenkins.io
    mui 左右滑动效果
    mui 日期控件的用法
    sql 不同where下的统计
    使用EF关于分页查询时遇到的一点疑问
    css按钮定位在div底部
  • 原文地址:https://www.cnblogs.com/pzw23/p/14005999.html
Copyright © 2011-2022 走看看