1、API 默认可以分辨 application/x-www-form-urlencoded 和 multipart/form-data 输入格式,查看 /api/config/main.php,request 应用程序组件的配置
'request' => [ 'csrfParam' => '_csrf-api', ],
2、在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:application/x-www-form-urlencoded,如图1
3、在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:multipart/form-data,如图2
4、在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:application/json,数据验证失败,如图3
{ "code": 20004, "message": "数据验证失败:Username不能为空。" }
5、配置 request 应用程序组件的 [[yii/web/Request::$parsers|parsers]] 属性使用 [[yii/web/JsonParser]] 用于JSON输入,此属性用于将原始HTTP请求主体转换为$bodyParams
'request' => [ 'csrfParam' => '_csrf-api', 'parsers' => [ 'application/json' => 'yii/web/JsonParser', ] ],
6、在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:application/x-www-form-urlencoded
{ "code": 10000, "message": "创建用户成功", "data": { "username": "444444", "email": "444444@163.com", "password_hash": "$2y$13$qXQwOfXLzPykyk/ymI3z3ua2WofRkrJT5NcmeiyUx8Iko51YdMeg.", "auth_key": "H8BmGgHLZRGd_1vvU8ESXrAi1pyaL-59", "status": 1, "created_at": 1532409559, "updated_at": 1532409559, "id": 19 } }
7、在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:multipart/form-data
{ "code": 10000, "message": "创建用户成功", "data": { "username": "555555", "email": "555555@163.com", "password_hash": "$2y$13$9NByl.XSlo/rzzmmUZWZT.k6Ncpk.br9py1PywpyXRjThsjEQaAMK", "auth_key": "tQuKPECDLAAqpjDc44CpCK7ynypuLbJ-", "status": 1, "created_at": 1532409634, "updated_at": 1532409634, "id": 20 } }
8、在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:application/json,如图4
{ "code": 10000, "message": "创建用户成功", "data": { "username": "666666", "email": "666666@163.com", "password_hash": "$2y$13$SmCEU6tS2qpwU3ggbAkWce5wMZP5BWtqkAgCd.vxbyjN3TwsX32d.", "auth_key": "D2aVPy___U-aySPYR-1-Y6msxipJulqE", "status": 1, "created_at": 1532409697, "updated_at": 1532409697, "id": 21 } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/250424.html