thinkjs接收get请求、post请求

    技术2023-07-14  65

    此文介绍使用 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.querythis.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.bodythis.post()

    前端使用umi-request发送请求:

    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); });

    拓展介绍:四种常见的 POST 提交数据方式

    吴迪软件开发 小程序 ECMAScript 6 React.js 金牛区吴迪软件开发工作室博客
    Processed: 0.010, SQL: 9