formidable_使用Formidable在Next.js API路由中使用文件数据

formidable

We will be checking on how we can use Formidable without the use of custom server, to send form data from the client side, to our backend

我们将检查如何在不使用自定义服务器的情况下使用Formidable,以将表单数据从客户端发送到后端

This example assumes you already comfortable in sending the file from the client side to your backend, a basic example of sending a file from client side will be :

本示例假设您已经可以轻松地从客户端向后端发送文件,从客户端发送文件的基本示例将是:

Next.js API (Next.js API)

The nice thing about Next.js API routes is that you can achieve many things without any use of a custom server. We’ll set up our api route that will handle our incoming form data.

Next.js API路由的好处是,无需使用自定义服务器就可以实现很多事情。 我们将设置将处理传入表单数据的api路由。

This is a basic setup of an api route in Next.js, in it we have req(request), in which there are built in middlewares which help us to parse the request in order to get access to the cookies, body of the request, queries in the request and all that jazz.

这是Next.js中api路由的基本设置,其中有req( request ) ,其中内置了中间件,这些中间件可以帮助我们解析请求以便访问cookie(请求正文) ,查询请求和所有爵士乐。

Then we also have res(response), which is our response helper, to send back a response after we done doing whatever we want to do with the request sent to this route.

然后,我们还有res( response ) (它是我们的响应帮助器),可以在完成对发送到此路由的请求的所有操作之后,发送回一个响应。

if you hit that endpoint; /api/uploadApi, you’ll get the ‘file received’ response.

如果达到那个终点; / api / uploadApi ,您将收到“文件已收到”响应。

Next.js also gives us an option to configure our api, with regards to the maximum size of the body parsed, and we can also tell it if we want our body parsed or not, in this instance, we need our form data as a stream, thus we’ll have to disable the bodyparser

Next.js还为我们提供了一个配置api的选项,涉及解析的正文的最大大小,我们还可以告诉它是否要解析正文,在这种情况下,我们需要将表单数据作为流,因此我们必须禁用bodyparser

Now that our setup is ready we can install all the dependencies will need to get our form data, which is micro and formidable.

现在我们的设置已经准备就绪,我们可以安装获取微型数据模型所需的所有依赖项。

Our file will now look like this:

现在,我们的文件将如下所示:

Micro will resolve the data for us, and formidable will handle all the incoming stream, then we store all the data to our ‘data’ variable. Should you want to send it to a database, you can create a readable stream and append it to form data then send it.

Micro将为我们解析数据,强大的将处理所有传入的流,然后将所有数据存储到我们的“ data”变量中。 如果要将其发送到数据库,则可以创建可读的流并将其附加到表单数据中然后发送。

翻译自: https://medium.com/javascript-in-plain-english/formidable-with-next-js-298c913517a0

formidable

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值