使用Promise封装request请求
Promise
对象是由关键字 new
及其构造函数来创建的。该构造函数会把一个叫做“处理器函数”(executor function)的函数作为它的参数。这个“处理器函数”接受两个函数——resolve
和 reject
——作为其参数。当异步任务顺利完成且返回结果值时,会调用 resolve
函数;而当异步任务失败且返回失败原因(通常是一个错误对象)时,会调用reject
函数。
想要某个函数拥有promise功能,只需让其返回一个promise即可。
const myFirstPromise = new Promise((resolve, reject) => {
// ?做一些异步操作,最终会调用下面两者之一:
//
// resolve(someValue); // fulfilled
// ?或
// reject("failure reason"); // rejected
});
export const request=(params) => {
// 定义公共的url
const baseUrl = "http://127.0.0.1:8080";
return new Promise((resolve,reject) => {
wx.request({
...params,
url:baseUrl+params.url,
success: (result) => {
resolve(result);
},
fail: (err) => {
reject(err);
}
});
})
}
wxml,使用两个button绑定发送请求事件
<button bindtap="submit">提交POST请求</button>
<button bindtap="submitGet">提交GET请求</button>
import {request} from '../../utils/request';
Page({
data: {
testEntity: {
id: '001',
name: 'kelvin',
account: 'account'
}
},
onLoad: function () {
},
submitGet(){
request({
url: "/testGet",
data: {
id: this.data.testEntity.id,
account: this.data.testEntity.account,
name: this.data.testEntity.name
},
})
.then(result => {
console.log(result.data);
})
},
submit(){
request({
url: "/testPost",
data: this.data.testEntity,
method: 'POST'
})
.then(result => {
console.log(result.data);
})
}
})
SpringBoot后台接收参数:
package com.example.demo.controller;
import com.example.demo.entity.TestEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin
public class WxRequestController {
@PostMapping("testPost")
//前后端testEntity属性名须一致
public String testPost(@RequestBody TestEntity testEntity){
System.out.println(testEntity.toString());
return "success";
}
@GetMapping("testGet")
public String testPost(@RequestParam String id, @RequestParam String account, @RequestParam String name){
System.out.println(id + "\t" + name + "\t" + account);
return "success";
}
}
注意:使用POST发送请求时,如果传递的参数是对象,这里直接对data进行赋值,即data : this.data.testEntity,GET请求与POST请求不同,data中是每一个参数的相对应,即:
data: {
id: this.data.testEntity.id,
account: this.data.testEntity.account,
name: this.data.testEntity.name
},
之前使用POST时犯了一个错误是这样的,这样导致springboot接收到的参数都是空的,这个就将POST与GET传参的形式混淆了
data: {
testEntity: this.data.entity
}