Nodejs solves 413 error

WBOY
Release: 2023-05-27 20:41:36
Original
864 people have browsed it

When developing web applications using Node.js, you may encounter situations where you need to handle large file uploads. However, when the uploaded file is too large, you may encounter an HTTP 413 Request Entity Too Large error. This is because Node.js has a request body size limit of 100KB by default. When the request entity size exceeds this limit, an HTTP 413 error occurs.

To solve this problem, there are several methods to choose from.

  1. Modify the request body limit

One solution is to increase the upload file size limit by modifying the default request body size limit. In Node.js, you can use the body-parser module to parse the request body. One of the options of this module is limit, which can be used to modify the request body size limit.

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

// limit设置为50MB
app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))

// 处理文件上传的请求
app.post('/upload', (req, res) => {
  // ...
})

app.listen(3000, () => {
  console.log('服务器启动成功')
})
Copy after login

Using the above code, the request body limit can be increased to 50MB. However, this method is not suitable for handling very large file upload requests, because the larger request body also consumes a lot of memory.

  1. Use Streams to process the request body

When the uploaded file is large, reading the entire request body into memory may cause performance issues. To avoid this problem, Node.js provides a Stream API that can process the request body as a stream.

The biggest difference between Stream and Buffer is that Stream can read data into memory in batches. In this way, even if the request body is very large, it will not put too much pressure on the server's memory.

const express = require('express')
const app = express()
const BUSBOY = require('busboy')

app.post('/upload', (req, res) => {
  const busboy = new BUSBOY({ headers: req.headers })
  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('文件名:', filename);
    file.on('data', function(data) {
      console.log('文件大小为:', data.length);
    });
    file.on('end', function() {
      console.log('文件上传成功');
    })
  })

  busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
    console.log('表单字段:', fieldname, val);
  })

  busboy.on('error', function(err) {
    console.log('文件上传失败:', err);
    res.status(500).send('文件上传失败')
  })

  req.pipe(busboy)
})
Copy after login

The above code uses the busboy library, which is a read-write stream API that can decompose the parsing of uploaded files into multiple stream events.

  1. Using Nginx

When using Node.js to handle large file upload requests, you can add an Nginx gateway server behind your application. Nginx can act as a reverse proxy, which can alleviate the problem of request body size limitations.

When the request body size exceeds the limit, Nginx can reject the request and return an HTTP 413 error. To adjust the Nginx configuration, add the following content to the /etc/nginx/nginx.conf file:

http {
  client_max_body_size 1000M;
  upstream app_servers {
    server localhost:3000;
  }
  server {
    listen 80;
    server_name yourdomain.com;
    location / {
      proxy_pass http://app_servers;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $host;
      proxy_set_header X-NginX-Proxy true;
    }
  }
}
Copy after login

Use client_max_body_size to modify the request body size limit. The above code sets the request body size limit to 1000MB.

Conclusion

When processing large file uploads, you may encounter the problem of HTTP 413 request entity being too large. In this article, we introduce three solutions: modifying the request body limit, using Streams to handle the request body, and using Nginx. You can choose the appropriate method for handling large file upload requests based on your application needs.

The above is the detailed content of Nodejs solves 413 error. For more information, please follow other related articles on the PHP Chinese website!

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 [email protected]
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!