Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
introduce
We have to deal with interfaces every day. There are many ways for interfaces to pass parameters. Today, we will briefly introduce how the front end passes parameters in query, body, path and FormData formats, and how the back end receives parameters. This tutorial tests requests through Postman, using the popular AXIos request library on the front end to simulate parameter incoming and node-koa2 on the back end to receive the passed parameters. Note: There are source links at the bottom
Query String Parameters — Query Parameters
- Query String Parameters commonly known as Query Parameters
This type of argument, commonly seen in Get requests, is passed as a URL string.
Request through Postman
Returned from the interfacectxQuery
That’s the argument we passed in
Request through AXIos
axios({
method: 'get'.url: '/query'.params: {
name: 'Joe'}});Copy the code
- View interface details in the browser
Receive parameters through KOA
router.get('/query'.(ctx, next) = > {
console.log(ctx.query); // Receive the query parameter
ctx.body = new SuccessRes({
method: ctx.request.method,
url: ctx.request.url,
ctxQuery: ctx.query
})
})
Copy the code
Request Payload – body parameter
- Request Payload Commonly known as the body parameter
This type of parameter, often used in POST requests, is passed in JSON format
Request through Postman
Returned from the interfacectxBody
That’s the argument we passed in
Request through AXIos
axios({
method: 'post'.url: '/body'.data: {
"phoneNumber": "18131239692"."veriCode": "0422"}})Copy the code
- View interface details in the browser
Receive parameters through KOA
router.post('/body'.async (ctx, next) => {
console.log(ctx.request.body);
ctx.body = new SuccessRes({
method: ctx.request.method,
url: ctx.request.url,
ctxBody: ctx.request.body
})
})
Copy the code
Path-path parameter
Path parameters are also known as route parameters. Those who have written VUE routes have probably seen routes in this form
const router = new VueRouter({
routes: [
// Dynamic path parameters start with a colon
{ path: '/user/:id'.component: User }
]
})
Copy the code
The route in the interface also means dynamic route
Request through Postman
Returned from the interfacectxParams
That’s the argument we passed in
Request through AXIos
axios({
method: 'get'.url: '/path/12',})Copy the code
- View interface details in the browser
Receive parameters through KOA
router.get('/path/:id'.async (ctx, next) => {
console.log(ctx.params);
ctx.body = new SuccessRes({
method: ctx.request.method,
url: ctx.request.url,
ctxParams: ctx.params
})
})
Copy the code
Form Data – formData parameter
- Form Data is commonly known as Form parameters
This type of parameter was passed by early web forms via action and is now commonly used as an interface for uploading files.
Request through Postman
Select upload picture, and other parameters
- Returned from the interface
fileList
It’s the file we passed in, the processed information - Returned from the interface
fields
Is the other form information we pass in
Request through AXIos
let formData = new FormData()
formData.append('file'.this.file) // Add data to the form object via append
formData.append('name'.'Form name') // Add additional data to the form
const res = await axios({
method: 'post'.url: '/formData'.headers: { 'Content-Type': 'multipart/form-data' },
data: formData
});
console.log(res.data);
Copy the code
- View interface details in the browser
Receive parameters through KOA
const formidable = require('formidable')
router.post('/formData'.async (ctx, next) => {
// console.log(ctx.req);
const res = await uploadFilesByFormidable(ctx.req)
console.log(res);
ctx.body = new SuccessRes({
method: ctx.request.method,
url: ctx.request.url, ... res }) })function uploadFilesByFormidable(req) {
return new Promise((resolve, reject) = > {
form.parse(req, (err, fields, files) = > {
// console.log({ fields, files });
const filesKeys = Object.keys(files)
const fileList = filesKeys.map(name= > {
const file = files[name]
return {
fileName: file.name || name,
filePath: file.path } }) resolve({ fields, fileList }) }); })}Copy the code
Multiple type parameter mixed request
The above interface request types can be used in combination, as shown in the examples below
Request through Postman
ctxQuery
Is the query argument we passedctxParams
Is the path argument we passedctxBody
Is the body argument we passed
Why not mix the form data parameters? FormData and JSON (the body parameter) are both body request parameters, so only one can occur.
Request through AXIos
axios({
method: 'post'.url: '/mixTheRequest/12'.params: {
name: 'Joe'.age: 23
},
data: {
"phoneNumber": "18131239692"."veriCode": "0422"}})Copy the code
- View interface details in the browser
conclusion
Query, body, path, FormData, and other methods of passing parameters are common, but you can continue to explore other methods.
Github source: github.com/ynzy/node-a…