此文介紹使用 thinkjs 如何擷取前端的請求參數。
文章目錄
- 筆者使用環境:
- 服務端對前端請求進行校驗
- 服務端接收前端的請求參數
- GET請求
- POST請求
筆者使用環境:
服務端:thinkjs
前端:react
請求:umi-request
服務端對前端請求進行校驗
檔案目錄: src/logic/user.js
請確定logic的目錄和controller目錄結構一緻
module.exports = class extends think.Logic {
checkTools(rules) {
// 想要拓展這個方法的話具體校驗内容可參考https://thinkjs.org/zh-cn/doc/3.0/logic.html
const msgs = {
required: '{name} 不能為空',
string: '{name} 必須是字元串類型',
array: '{name} 必須是數組類型',
boolean: '{name} 必須是布爾類型',
int: '{name} 必須是整數',
float: '{name} 必須是浮點數類型',
object: '{name} 必須是對象類型'
};
const flag = this.validate(rules, msgs);
if (!flag) {
return this.fail(1002, '參數校驗失敗', this.validateErrors);
}
}
addUserAction() {
this.allowMethods = 'post'; // 如果請求不是post的話會直接終止後續操作傳回前端錯誤。
return this.checkTools({
name: { required: true, string: true, trim: true },
}) // 調用自定義的方法進行校驗參數
}
}
服務端接收前端的請求參數
GET請求
thinkjs服務端這邊可以通過倆種方法擷取:
- this.ctx.request.query
- this.get()
前端使用umi-request發送請求:
import umiRequest from 'umi-request';
// 省略了非關鍵代碼
// 第一種請求加參數的方法
umiRequest.get('http://127.0.0.1:8360/user/queryUsers?id=2&name=3')
.then((response) => {
console.log(response)
})
.catch(err => {
console.log(err);
});
// 第二種請求加參數的方法
umiRequest.get('http://127.0.0.1:8360/user/queryUsers', {
params: { id: 111, name: '吳迪' }
})
.then((response) => {
console.log(response)
})
.catch(err => {
console.log(err);
});
POST請求
thinkjs服務端這邊可以通過倆種方法擷取:
- this.ctx.request.body
- this.post()
import umiRequest from 'umi-request';
// 省略了非關鍵代碼
umiRequest.post('http://127.0.0.1:8360/user/editUser', {
body: vals,
headers: {
"Content-Type": "application/json;"
}
})
.then((response) => {
console.log(response);
})
.catch(err => {
console.log(err);
});