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));
如果不想直接拼接参数,可以如下面这样,可以防止url注入
const ur = new URL( `${this.ipAddress}/api/beast/zhcx/zhcxIndex/`, window.location.href ); ur.searchParams.append("ipObj", this.hostIpObj.ip); ur.searchParams.append("page", page); ur.searchParams.append("size", this.pageSize); fetch(ur, { 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) => {
//获取数据
}) .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) );