express中间件

    科技2022-08-02  153

    express中间件

    Express.js is a Javascript framework used for developing the server side for web applications and APIs. A middleware in the literal sense means anything that is in the middle of two layers of software. In full-stack applications, middlewares are in the middle of the client and the server. In Express.js, they are functions that execute during requests from the client, to the server.

    Express.js是一个Javascript框架,用于为Web应用程序和API开发服务器端。 从字面上看,中间件是指位于两层软件中间的任何内容。 在全栈应用程序中,中间件位于客户端和服务器的中间。 在Express.js中,它们是在从客户端到服务器的请求期间执行的函数。

    When writing Express Middlewares, it gives the function the capability to access the request and response object within the HTTP request cycle, in case there is a task that needs to be executed during the communications between the client and the server.

    在编写Express Middlewares时,如果在客户端与服务器之间的通信过程中需要执行任务,则该功能使该功能能够在HTTP请求周期内访问请求和响应对象。

    When developing a full-stack application, web developers know there can be constant communications between the client and the server. Sometimes, those communications can be lost or corrupted if not handled in a way that makes sure requests from the client are able to get a response from the server. This is where middlewares come in when developing a full-stack application.

    在开发全栈应用程序时,Web开发人员知道客户端与服务器之间可以保持持续的通信。 有时,如果不以确保来自客户端的请求能够从服务器获得响应的方式进行处理,则这些通信可能会丢失或损坏。 这是开发全栈应用程序时中间件进入的地方。

    Let’s say you’re creating a web application that includes uploading images, along with adding detailed information about the image. Image upload will utilize middlewares. There are a few different methods you can use, but for this example, we will be using the middleware Multer. Multer is used for handling the form-data object, which is primarily used for file uploading. This middleware adds a body and file object to the request object in an HTTP request. The body object contains the text and file object.

    假设您正在创建一个Web应用程序,其中包括上载图像以及添加有关图像的详细信息。 图像上传将利用中间件。 您可以使用几种不同的方法,但是在此示例中,我们将使用中间件Multer。 Multer用于处理表单数据对象,该对象主要用于文件上传。 该中间件将主体和文件对象添加到HTTP请求中的请求对象中。 主体对象包含文本和文件对象。

    If the form-data object sounds familiar, take a look at Postman (if you’re using it) and click ‘body’.

    如果表单数据对象听起来很熟悉,请查看Postman(如果正在使用它),然后单击“正文”。

    Notice the body HTTP object has the form-data object, with a set of key and value pairs. This request is sent from the client. Within code, this request will look like this:

    注意,主体HTTP对象具有带一组键和值对的form-data对象。 该请求是从客户端发送的。 在代码中,此请求将如下所示:

    const formData = new FormData()formData.append(‘cityImage’, image)

    This code is within a submit function, which then calls an Axios post request, which takes in the formData object as a parameter.

    这段代码位于Submit函数中,该函数随后调用Axios发布请求,该请求将formData对象作为参数。

    const addCity = (newCity) => { const config = { headers: { 'content-type': 'multipart/form-data' } } axios.post('/api/files', newCity, config) .then(res => /*insert code here*/) .catch(err => console.log(err)) console.log(cities) }

    Axios is used to fire off that HTTP request from the client to the server. When this happens is when the middleware magic comes into play. Typically in a separate file from the server, we have a file for our middleware functions. With each HTTP request (GET, POST, DELETE as the most common) we can include middleware functions.

    Axios用于触发从客户端到服务器的HTTP请求。 这种情况发生在中间件魔术发挥作用的时候。 通常,在与服务器不同的文件中,我们有一个用于中间件功能的文件。 对于每个HTTP请求(最常见的是GET,POST,DELETE),我们可以包括中间件功能。

    Include Express and Multer for your image uploading

    包括Express和Multer用于上传图片

    const express = require('express')const multer = require('multer')const DIR = './uploads/'const storage = multer.diskStorage({ //diskStorage is used to define destination and filename destination: (req, file, cb) => { cb(null, DIR); }, filename: (req, file, cb) => { const fileName = file.originalname.toLocaleLowerCase().split(' ').join('.') cb(null, fileName) }})let upload = multer({ storage: storage })

    Use diskStorage to save the file to a folder destination of your choice. The fileName can also be a name of your choice.

    使用diskStorage将文件保存到您选择的文件夹目标中。 fileName也可以是您选择的名称。

    Now is where you declare when there is a post request, to complete an action, in between that request and response.

    现在,您可以在此位置声明发布请求,以在该请求和响应之间完成操作。

    const cityRouter = express.Router()cityRouter.post("/files", upload.single('cityImage') ,(req,res,next) =>{ const url = req.protocol + '://' + req.get('host') const newCity = new City({ _id: new mongoose.Types.ObjectId(), cityImage:url + '/uploads/' + req.file.filename});newCity .save() .then(result => { console.log(result); res.status(201).json({ message: "Created city", createdCity :{ _id: result._id, cityImage:result.cityImage } }) })})

    This post request has the upload Multer variable, holding our uploaded image. This will create a city object within our MongoDB (which we won’t get into in this article), with a link to the uploaded image.

    该帖子请求具有上载Multer变量,其中包含我们上载的图像。 这将在我们的MongoDB中创建一个city对象(我们将不在本文中介绍),并带有指向上载图像的链接。

    As long as your object being posted to Mongo matches your Mongo schema, you should be good to go!

    只要您发布到Mongo的对象与您的Mongo模式匹配,您就应该很好!

    翻译自: https://medium.com/@patricemblocker/file-upload-and-middlewares-in-express-js-2db02b39d2e

    express中间件

    Processed: 0.011, SQL: 8