使用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
}