What are node middlewares?

藏色散人
Release: 2021-12-10 13:52:34
Original
3681 people have browsed it

Node middleware includes: 1. koa-bodyparser; 2. koa-body; 3. Static resource manager koa-static; 4. cors; 5. koa-cors; 6. koa-cors2 setting request Wait.

What are node middlewares?

The operating environment of this article: Windows 7 system, nodejs version 10.16.2, Dell G3 computer.

What are the node middlewares?

Node middleware type:

Node middleware is the function of processing http requests encapsulated in the program. Node middleware is executed in the pipeline. Middleware sits on top of the client/server operating system and manages computer resources and network communications.

Middleware serves the main logical business and can be divided into: application-level middleware, routing-level middleware, built-in middleware, third-party middleware, and error-level middleware.

Commonly used middleware in node:

In the process of learning node, I have accumulated many useful middleware. Most of these middlewares need to be used with koa

1, koa-bodyparser

This plug-in is used to parse the parameters brought by the front-end post request

//入口文件
const bodyParser = require('koa-bodyparser');
app.use(bodyParser({//设置可以接收的数据类型
    enableTypes:['json', 'form', 'text']
}))
async function (ctx) {
    console.log(ctx.request.body)
    ctx.req.on('data',(data) => {
        console.log(JSON.parse(data),'文件')
    })
}
Copy after login

is not introduced In the case of koa-bodyparser, parameters can only be obtained through ctx.req.on('data',callback)

. After introducing middleware, parameters can be obtained as long as ctx.request.body. Much more convenient than the first one.

2. koa-body

This plug-in is used to obtain the files and file information uploaded in the request, such as pictures and zip files

const koaBody    = require('koa-body')
app.use(koaBody({
        multipart: true,
        formidable: {
            maxFileSize: 20 * 1024 * 1024    // 设置上传文件大小最大限制,默认2M
        }
    }))
Copy after login

It can be used during the processing of the request Information about all uploaded files can be obtained directly through ctx.request.files.

Notice! ! ! After using koa-body, do not use koa-bodyparser. It will conflict, causing the status code returned by the front-end post request to be canceled

3. The static resource manager koa-static

was tested locally. At that time, I uploaded a picture, and then printed the picture address to be a long string of c://.../name/.png. Although it can be accessed locally, it will not work if it is placed on the server!

By introducing koa-static, you can specify the static file address to a folder on the project path and then access the image directly through the port monitored by koa at http://192.168.0.177:3030/name.png

const koaStatic  = require('koa-static')
app.use(koaStatic('./public'))//括号中是设置的静态文件路径
Copy after login

4, cors, koa-cors, koa-cors2 set request headers

I basically use these middlewares to configure cross-domain and request header information

const cors       = require('koa2-cors') 
app.use(cors({
    exposeHeaders: ['multipart/form-data','application/x-www-form-urlencoded']
}))
Copy after login

You can set the parameters yourself or you can directly apply app.use(cors()) without setting parameters to cross domain.

Speaking of cross-domain here, let me mention the cross-domain setting method of native node (you can also set various configurations of the request header)

app.use(async (ctx, next) => {
   ctx.set('Access-Control-Allow-Origin', ctx.headers.origin)//'*'有可能会问题
   ctx.set('Access-Control-Allow-Credentials', 'true')
   ctx.set('Access-Control-Allow-Headers', 'Origin ,multipart/form-data, X-Requested-With, Content-Type, Accept')
   await next()
})
Copy after login

If you encounter any useful ones in the future The middleware will record again! ! !

Recommended learning: "node.js Video Tutorial"

The above is the detailed content of What are node middlewares?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!