Express

Express

Express is a minimal and flexible Node.js web application framework, providing a robust set of features for building web applications.
Kevin  Simon

Kevin Simon

1663229908

Validate Rest API in Node.js and Express

In this tutorial we will learn how to validate rest API data on Node.js, Express app using Express-Validator Module.

Table Of Contents

1 : Install Express-Validator and Body Parser Module

2 : Create Validation.js File

3 : Import Installed Modules in Server.js

4 : Start App Server

5 : Test Apis


1 : Install Express-Validator and Body Parser Module

Install express-validator, cors and body-parser modules into your node js express application by executing the following command on command prompt:

npm install body-parser --save

npm install express-validator cors --save

2 : Create Validation.js File

Create validation.js and import the express-validator modules in it. So visit your app root directory and create validation.js and validate fields; as following:

const { check } = require('express-validator');
 
exports.signupValidation = [
    check('name', 'Name is requied').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
    check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
]
 
exports.loginValidation = [
     check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
     check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
 
]

3 : Import Installed Modules in Server.js

Create server.js/index.js file into your app root directory and import above installed modules; as following:

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const { signupValidation, loginValidation } = require('./validation.js');
 
const app = express();
 
app.use(express.json());
 
app.use(bodyParser.json());
 
app.use(bodyParser.urlencoded({
    extended: true
}));
 
app.use(cors());
 
app.get('/', (req, res) => {
    res.send('Node js file upload rest apis');
});
 
app.post('/register', signupValidation, (req, res, next) => {
   // your registration code
});
 
 
app.post('/login', loginValidation, (req, res, next) => {
   // your login code
});
 
// Handling Errors
app.use((err, req, res, next) => {
    // console.log(err);
    err.statusCode = err.statusCode || 500;
    err.message = err.message || "Internal Server Error";
    res.status(err.statusCode).json({
      message: err.message,
    });
});
 
app.listen(3000,() => console.log('Server is running on port 3000'));

4 : Start App Server

Open your command prompt and execute the following command to run node js express file upload application:

//run the below command

node sever.js

5 : Test Apis

Open postman app and test apis validation in Node.js Express app:

In this tutorial, you have learned how to validate rest API data on node js express app using express-validator module.

#nodejs #express #javascript 

Validate Rest API in Node.js and Express
Code  JS

Code JS

1662776032

Build a Webshop or E-Commerce Store using Angular, TypeScript, Express and Stripe

Build a Webshop! In this tutorial, we are going to build a webshop or e-commerce store using Angular/TypeScript, Express.js, and Stripe. We are gonna learn how to use Angular material and Tailwind to structure our UI and how to integrate store API into our app.

Also at the end, we will build a checkout, and we are gonna integrate Stripe so that we can process payments.

Links: 
Code: https://github.com/bobangajicsm/E-Commerce-Store 
Fake store API: https://fakestoreapi.com/ 
Stripe: https://stripe.com/ 
Prebuilt checkout page: https://stripe.com/docs/checkout/quickstart 
Stripe Shipping Code: https://stripe.com/docs/payments/checkout/shipping 

Subscribe: https://www.youtube.com/c/CodewithSloba/featured 

#javascript #angular #nodejs #express  

Build a Webshop or E-Commerce Store using Angular, TypeScript, Express and Stripe
Gordon  Taylor

Gordon Taylor

1662048600

An Unopinionated Authentication Library for Building Node.js APIs

Permit

An unopinionated authentication library for building Node.js APIs.

Permit makes it easy to add an authentication layer to any Node.js API. It can be used with any of the popular server frameworks (eg. Express, Koa, Hapi, Fastify) and it can be used for any type of API (eg. REST, GraphQL, etc.) due to its simple, unopinionated design.

Usage

Permit lets you authenticate via the two schemes most APIs need: a single secret bearer token, or a set of username and password credentials. For example, here's how to authenticate a bearer token:

import { Bearer } from 'permit'

// A permit that checks for HTTP Bearer Auth, falling back to a query string.
const permit = new Bearer({
  query: 'access_token',
})

async function handler({ req, res }) {
  // Try to find the bearer token in the request.
  const token = permit.check(req)

  // No token, that means they didn't pass credentials!
  if (!token) {
    permit.fail(res)
    throw new Error(`Authentication required!`)
  }

  // Authenticate the token however you'd like...
  const user = await db.users.findByToken(token)

  // No user, that means their credentials were invalid!
  if (!user) {
    permit.fail(res)
    throw new Error(`Authentication invalid!`)
  }

  // They were authenticated, so continue with your business logic...
  ...
}

Since Permit isn't tightly coupled to a framework or data model, it gives you complete control over how you write your authentication logic—the exact same way you'd write any other request handler.

Why?

Before Permit, the only real choice for authentication libraries in Node.js was Passport.js. But it has a bunch of issues that complicate your codebase...

It is not focused on authenticating APIs. Passport is focused on authenticating web apps with services like Facebook, Twitter and GitHub. APIs don't need that, so all the extra bloat means lots of complexity for no gain.

It is tightly-coupled to Express. If you use Koa, Hapi, Fastify, or some other framework you have to go to great lengths to get it to play nicely. Even if you just want to tweak the opinionated defaults you're often out of luck.

Other middleware are tightly-coupled to it. Passport stores state on the req object, so all your other middleware (even other third-party middleware) become tightly coupled to its implementation, making your codebase brittle.

It results in lots of hard to debug indirection. Because of Passport's black-box architecture, whenever you need to debug an issue it's causing you have to trace its logic across many layers of indirection and many repositories.

It's not very actively maintained. Passport's focus on OAuth providers means that it takes on a huge amount of scope, across a lot of repositories, many of which are not actively maintained anymore.

Don't get me wrong, Passport works great for working with OAuth providers. But if you've run into any of these problems before while adding authentication to a Node.js API, you might like Permit.

Which brings me to how Permit solves these issues…

Principles

API first. Permit was designed with authenticating APIs in mind, so it's able to be much leaner than others, since it doesn't need to handle complex OAuth integrations with Facebook, Google, etc.

Stateless requests. Since the vast majority of APIs are stateless in nature, Permit eschews the complexity that comes with handling session stores—without preventing you from using one if you need to.

Framework agnostic. Permit doesn't lock you into using any specific server framework or data model, because it's composed of small but powerful utility functions that do the heavy-lifting for you.

Unopinionated interface. Due to its simple interface, Permit makes it much easier to write and reason about your actual authentication logic, because it's exactly like writing any other route handler for your API.

Examples

Permit's API is very flexible, allowing it to be used for a variety of use cases depending on your server framework, your feelings about ORMs, your use of promises, etc. Here are a few examples of common patterns...

Documentation

Read the getting started guide to familiarize yourself with how Permit works, or check out the full API reference for more detailed information...

Thanks

Thank you to @dresende for graciously transferring the permit package!

Download Details:

Author: ianstormtaylor
Source Code: https://github.com/ianstormtaylor/permit 
License: MIT license

#javascript #nodejs #express 

An Unopinionated Authentication Library for Building Node.js APIs
Reid  Rohan

Reid Rohan

1661889600

Opencv-express: Template for using Opencv-3.4.1 + Opencv-contrib

opencv-express

This is an example of how to use opencv4nodejs in your web apps with express.js or any other serverside node.js framework. A minimalistic docker image is provided with opencv-3.4.1 and opencv_contrib-3.4.1 + node.js environment set up (opencv4nodejs globally installed).

Build the image:

docker-compose build

Run:

docker-compose up

Docker image:

~353mb (compressed size: ~124mb)

  • ubuntu: 16.04
  • nodejs: v9.8.0
  • npm: v5.6.0
  • opencv4nodejs: 3.3.1

Set up your own image:

If you want to build your own docker image or use a different OpenCV version, you can pull one of the OpenCV 3.x base images: https://hub.docker.com/u/justadudewhohacks/.

Download Details:

Author: justadudewhohacks
Source Code: https://github.com/justadudewhohacks/opencv-express 
License: MIT license

#javascript #opencv #express #node 

Opencv-express: Template for using Opencv-3.4.1 + Opencv-contrib
Michael Kitas

Michael Kitas

1661872278

Nodejs Puppeteer Tutorial #13 - Vercel Deployment CLI & GitHub

🧾This puppeteer tutorial is designed for beginners to learn how to use the node js puppeteer library to perform web scraping, web testing, and create website bots. Puppeteer is a Node library that provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default but can be configured to run full (non-headless) Chrome or Chromium.

⭐ Tags ⭐ - Nodejs Tutorials - Puppeteer Nodejs - Nodejs puppeteer tutorial - Puppeteer Tutorial for Beginners 
⭐ Hashtags ⭐ #nodejs  #javascript #node #web-development #express #dev 

Nodejs Puppeteer Tutorial #13 - Vercel Deployment CLI & GitHub
Reid  Rohan

Reid Rohan

1661854740

Cognito-Express: API Authentication with AWS Congito

Cognito-Express: API Authentication with AWS Congito

Synopsis

cognito-express authenticates API requests on a Node.js application (either running on a server or in an AWS Lambda function) by verifying the JWT signature of AccessToken or IDToken generated by Amazon Cognito.

Architecture

Motivation

Architecture

This module lets you authenticate Node.js API requests by verifying the JWT signature of AccessToken or IDToken - without needing to call Amazon Cognito for each API invocation.

The module can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

This module essentially bundles steps 1-7 listed on the official AWS documentation on Using ID Tokens and Access Tokens in your Web APIs

  1. Download and store the JSON Web Token (JWT) set for your user pool.
  2. Decode the token string into JWT format.
  3. Check the iss claim. It should match your user pool.
  4. Check the tokenUse claim. It should match your set preference for access or id token types
  5. Get the kid from the JWT token header and retrieve the corresponding JSON Web Key that was stored in step 1.
  6. Verify the signature of the decoded JWT token.
  7. Check the exp claim and make sure the token is not expired.

You can now trust the claims inside the token and use it as it fits your requirements.

Prerequisites

After successful authentication of a user, Amazon Cognito issues three tokens to the client:

  • ID token
  • Access token
  • Refresh token

(Note: The login mechanism is not covered by this module and you'll have to build that separately)

Save these tokens within the client app (preferably as cookies). When any API is invoked from client, pass in the AccessToken or IDToken to the server.

It's completely up to you how you pass in the AccessToken or IDToken. Here are two options:

  1. By adding them explicitly in Request Headers
  2. Just save the tokens as cookies. This way they get attached to request headers whenever APIs are invoked.

Configuration

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    region: "us-east-1",
    cognitoUserPoolId: "us-east-1_dXlFef73t",
    tokenUse: "access", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

Usage

cognitoExpress.validate(accessTokenFromClient, function(err, response) {
    if (err) {
        /*
            //API is not authenticated, do something with the error.
            //Perhaps redirect user back to the login page
            
            //ERROR TYPES:
            
            //If accessTokenFromClient is null or undefined
            err = {
                "name": "TokenNotFound",
                "message": "access token not found"
            }
            
            //If tokenuse doesn't match accessTokenFromClient
            {
                "name": "InvalidTokenUse",
                "message": "Not an id token"
            }

            //If token expired
            err = {
                "name": "TokenExpiredError",
                "message": "jwt expired",
                "expiredAt": "2017-07-05T16:41:59.000Z"
            }

            //If token's user pool doesn't match the one defined in constructor
            {
                "name": "InvalidUserPool",
                "message": "access token is not from the defined user pool"
            }

        */
    } else {
        //Else API has been authenticated. Proceed.
        res.locals.user = response; //Optional - if you want to capture user information
        next();
    }
});

Also supports async/await pattern

(async function main() {
  try {
    const response = await cognitoExpress.validate(accessTokenFromClient);
    console.log(response);
     //User is authenticated, proceed with rest of your business logic.

  } catch (e) {
    console.error(e);
     //User is not authenticated, do something with the error.
     //Perhaps redirect user back to the login page
  }
})();

Full Example

app.js - server

//app.js
"use strict";

const express = require("express"),
    CognitoExpress = require("cognito-express"),
    port = process.env.PORT || 8000;

const app = express(),
    authenticatedRoute = express.Router(); //I prefer creating a separate Router for authenticated requests

app.use("/api", authenticatedRoute);

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    region: "us-east-1",
    cognitoUserPoolId: "us-east-1_dXlFef73t",
    tokenUse: "access", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
authenticatedRoute.use(function(req, res, next) {
    
    //I'm passing in the access token in header under key accessToken
    let accessTokenFromClient = req.headers.accesstoken;

    //Fail if token not present in header. 
    if (!accessTokenFromClient) return res.status(401).send("Access Token missing from header");

    cognitoExpress.validate(accessTokenFromClient, function(err, response) {
        
        //If API is not authenticated, Return 401 with error message. 
        if (err) return res.status(401).send(err);
        
        //Else API has been authenticated. Proceed.
        res.locals.user = response;
        next();
    });
});


//Define your routes that need authentication check
authenticatedRoute.get("/myfirstapi", function(req, res, next) {
    res.send(`Hi ${res.locals.user.username}, your API call is authenticated!`);
});

app.listen(port, function() {
    console.log(`Live on port: ${port}!`);
});

client.js - angular example

//client.js - angular example

"use strict";

//I stored my access token value returned from Cognito in a cookie called ClientAccessToken

app.controller("MyFirstAPI", function($scope, $http, $cookies) {
    $http({
        method: "GET",
        url: "/api/myfirstapi",
        headers: {
            accesstoken: $cookies.get("ClientAccessToken") 
            }
        }
    }).then(
        function success(response) {
            //Authenticated. Do something with the response. 
        },
        function error(err) {
            console.error(err);
        }
    );
});

Contributors

Gary Arora

Download Details:

Author: ghdna
Source Code: https://github.com/ghdna/cognito-express 
License: MIT license

#javascript #express #nodejs #aws #jwt 

Cognito-Express: API Authentication with AWS Congito

Como Corrigir O Erro "413 Request Entity too Large" No Node.js

Recentemente, tive que lidar com o erro expresso “413 Request Entity Too Large”. Após algumas pesquisas, descobri que este é um problema bastante comum que pode ocorrer por dois motivos gerais. Em ambos os casos, o erro é gerado pelo servidor quando um cliente faz uma solicitação considerada muito grande.

Vamos agora aprender tudo o que você precisa saber sobre o erro “413 Request Entity Too Large” e ver como corrigi-lo no Express.

 

O que é o erro “413 Request Entity Too Large”?

Conforme explicado em MDN , o código de status de resposta HTTP 413 Payload Too Largeindica que a entidade de solicitação executada pelo cliente é maior que os limites definidos pelo servidor. Como resultado disso, o servidor pode fechar a conexão ou retornar um Retry-Aftercampo de cabeçalho.

O HTTP 413 Payload Too Largeera chamado anteriormente413 Request Entity Too Large . Observe que a maioria dos sistemas ainda o chama dessa maneira. Portanto, se você encontrar uma mensagem de erro “Request Entity Too Large”, você pode assumir que está lidando com um 413 Payload Too Largeerro HTTP.

 

Por que ocorre o erro HTTP 413?

Conforme explicado anteriormente, um erro HTTP 413 ocorre quando a solicitação do cliente é maior do que o servidor deseja ou pode processar. Especificamente, isso pode acontecer por dois motivos. Vamos cavar neles.

1. Servidor Web mal configurado

Você recebe um erro HTTP 413 porque a solicitação do cliente excede o limite de tamanho definido na configuração do seu servidor web. Por exemplo, o limite de tamanho de solicitação do cliente imposto pelo Nginx por padrão é definido como 1 MB . Portanto, se você não configurar o Nginx para esperar explicitamente um valor maior, receberá um erro HTTP 413 para qualquer solicitação maior que 1 MB.

2. Servidor de aplicativos mal configurado

Você recebe um erro HTTP 413 porque a solicitação do cliente excede o limite de tamanho definido na configuração do servidor de aplicativos. Por exemplo, um aplicativo Express em um servidor Node.js limita o corpo da solicitação JSON a 100 KB por padrão. Portanto, se você não configurar o Express para esperar explicitamente um valor maior, receberá um erro HTTP 413 para qualquer solicitação JSON maior que 100 KB.

Neste artigo, você aprenderá como lidar com erros HTPP 413 causados ​​pela segunda causa, ou seja, um servidor de aplicativos mal configurado. Se você quiser se aprofundar na segunda causa, confira este artigo .

Corrigindo o erro “413 Request Entity Too Large” no Express

Para corrigir o erro “413 Request Entity Too Large” em um aplicativo Express, basta atualizar o arquivo de inicialização do servidor. Isso geralmente é chamado index.jsou server.jse é onde você inicializa o servidor Express. Certifique-se de que este arquivo contém as seguintes linhas:

// index.js or server.js

const express = require("express")

// ...
    
const app = express()

// ...

// fixing "413 Request Entity Too Large" errors
app.use(express.json({limit: "10mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))

// ...

Essas duas últimas linhas de código estendem o tamanho do payload JSON e dos parâmetros de consulta de URL para 10 MB. Isso deve ser suficiente para evitar a maioria dos erros “413 Request Entity Too Large” em seu aplicativo Express. Configure os dois valores limite de acordo com suas necessidades, mas sem superdimensioná-los desnecessariamente.

E voilà! Você acabou de aprender como resolver o erro “413 Request Entity Too Large” em um aplicativo Node.js Express.

 

Conclusão

Neste artigo, você aprendeu o que é um erro HTTP 413, por que ele ocorre e como resolvê-lo. Especificamente, você viu como corrigir a “413 Request Entity Too Large” em um servidor Node.js Express. Este é um problema particularmente comum que ocorre quando a solicitação do cliente é maior do que o servidor espera. Como mostrado, são necessárias apenas algumas linhas de código para resolvê-lo.

Obrigado por ler! Espero que você tenha achado este artigo útil. Fique à vontade para deixar dúvidas, comentários ou sugestões.

Fonte: https://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

Como Corrigir O Erro "413 Request Entity too Large" No Node.js

Corregir El Error "413 Entidad De Solicitud Demasiado Grande" En Node

Recientemente tuve que lidiar con el error Express "Entidad de solicitud 413 demasiado grande". Después de investigar un poco, descubrí que este es un problema bastante común que puede ocurrir por dos razones generales. En ambos casos, el servidor arroja el error cuando un cliente realiza una solicitud que se considera demasiado grande.

Ahora aprendamos todo lo que necesita saber sobre el error "Entidad de solicitud 413 demasiado grande" y veamos cómo solucionarlo en Express.

 

¿Qué es el error "Entidad de solicitud 413 demasiado grande"?

Como se explica en MDN , el código de estado de respuesta HTTP 413 Payload Too Largeindica que la entidad de solicitud realizada por el cliente es mayor que los límites definidos por el servidor. Como resultado de esto, el servidor podría cerrar la conexión o devolver un Retry-Aftercampo de encabezado.

413 Payload Too LargeAnteriormente se llamaba413 Request Entity Too Large HTTP . Tenga en cuenta que la mayoría de los sistemas todavía lo llaman de esa manera. Por lo tanto, si se encuentra con un mensaje de error de "Entidad de solicitud demasiado grande", puede asumir que se trata de un 413 Payload Too Largeerror HTTP.

 

¿Por qué ocurre el error HTTP 413?

Como se explicó anteriormente, se produce un error HTTP 413 cuando la solicitud del cliente es más grande de lo que el servidor está dispuesto o puede procesar. Específicamente, esto puede suceder debido a dos razones. Profundicemos en ellos.

1. Servidor web mal configurado

Obtiene un error HTTP 413 porque la solicitud del cliente excede el límite de tamaño definido en la configuración de su servidor web. Por ejemplo, el límite de tamaño de la solicitud del cliente impuesto por Nginx de forma predeterminada se establece en 1 MB . Por lo tanto, si no configura Nginx para esperar explícitamente un valor mayor, obtendrá un error HTTP 413 para cualquier solicitud de más de 1 MB.

2. Servidor de aplicaciones mal configurado

Obtiene un error HTTP 413 porque la solicitud del cliente supera el límite de tamaño definido en la configuración del servidor de aplicaciones. Por ejemplo, una aplicación Express en un servidor Node.js limita el cuerpo de la solicitud JSON a 100 Kb de forma predeterminada. Por lo tanto, si no configura Express para esperar explícitamente un valor mayor, obtendrá un error HTTP 413 para cualquier solicitud JSON de más de 100 Kb.

En este artículo, aprenderá cómo abordar los errores HTTP 413 causados ​​por la segunda causa, es decir, un servidor de aplicaciones mal configurado. Si quieres profundizar en la segunda causa, consulta este artículo .

Corrección del error "413 Entidad de solicitud demasiado grande" en Express

Para corregir el error “413 Entidad de solicitud demasiado grande” en una aplicación Express, solo tiene que actualizar el archivo de inicialización del servidor. Esto generalmente se llama index.jso server.jsy es donde inicializa el servidor Express. Asegúrese de que este archivo contenga las siguientes líneas:

// index.js or server.js

const express = require("express")

// ...
    
const app = express()

// ...

// fixing "413 Request Entity Too Large" errors
app.use(express.json({limit: "10mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))

// ...

Estas dos últimas líneas de código amplían el tamaño de la carga útil de JSON y los parámetros de consulta de URL a 10 MB. Esto debería ser suficiente para evitar la mayoría de los errores de "Entidad de solicitud 413 demasiado grande" en su aplicación Express. Configure los dos valores límite según sus necesidades, pero sin sobredimensionarlos innecesariamente.

Et voila! Acaba de aprender a resolver el error "413 Entidad de solicitud demasiado grande" en una aplicación Node.js Express.

 

Conclusión

En este artículo, aprendió qué es un error HTTP 413, por qué ocurre y cómo solucionarlo. Específicamente, vio cómo corregir la "Entidad de solicitud 413 demasiado grande" en un servidor Node.js Express. Este es un problema particularmente común que ocurre cuando la solicitud del cliente es más grande de lo que espera el servidor. Como se muestra, solo se necesitan un par de líneas de código para resolverlo.

¡Gracias por leer! Espero que hayas encontrado útil este artículo. No dude en dejar cualquier pregunta, comentario o sugerencia.

Fuente: https://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

Corregir El Error "413 Entidad De Solicitud Demasiado Grande" En Node
Trung  Nguyen

Trung Nguyen

1661562000

Cách Khắc Phục Lỗi “413 Đối Tượng Yêu Cầu Quá Lớn” Trong Node.js

Gần đây, tôi đã phải đối phó với lỗi Express "413 Đối tượng Yêu cầu Quá lớn". Sau một số nghiên cứu, tôi phát hiện ra rằng đây là một vấn đề khá phổ biến có thể xảy ra vì hai lý do chung. Trong cả hai trường hợp, lỗi do máy chủ tạo ra khi máy khách đưa ra một yêu cầu được coi là quá lớn.

Bây giờ chúng ta hãy tìm hiểu mọi thứ bạn cần biết về lỗi “413 Đối tượng Yêu cầu Quá lớn” và xem cách khắc phục lỗi này trong Express.

 

Lỗi “Đối tượng yêu cầu 413 quá lớn” là gì?

Như đã giải thích trong MDN , mã trạng thái phản hồi HTTP 413 Payload Too Largechỉ ra rằng thực thể yêu cầu do máy khách thực hiện lớn hơn giới hạn do máy chủ xác định. Do đó, máy chủ có thể đóng kết nối hoặc trả về Retry-Aftertrường tiêu đề.

HTTP trước đây 413 Payload Too Largeđã được gọi413 Request Entity Too Large . Lưu ý rằng hầu hết các hệ thống vẫn gọi nó như vậy. Do đó, nếu bạn gặp thông báo lỗi "Yêu cầu đối tượng quá lớn", bạn có thể cho rằng mình đang 413 Payload Too Largegặp lỗi HTTP.

 

Tại sao lỗi HTTP 413 xảy ra?

Như đã giải thích trước đó, lỗi HTTP 413 xảy ra khi yêu cầu của máy khách lớn hơn mức máy chủ sẵn sàng hoặc có thể xử lý. Cụ thể, điều này có thể xảy ra bởi vì hai lý do. Hãy cùng tìm hiểu chúng.

1. Máy chủ web được cấu hình kém

Bạn gặp lỗi HTTP 413 vì yêu cầu máy khách vượt quá giới hạn kích thước được xác định trong cấu hình máy chủ web của bạn. Ví dụ: giới hạn kích thước yêu cầu khách hàng do Nginx áp đặt theo mặc định được đặt thành 1 MB . Do đó, nếu bạn không định cấu hình Nginx để mong đợi giá trị lớn hơn một cách rõ ràng, bạn sẽ gặp lỗi HTTP 413 cho bất kỳ yêu cầu nào lớn hơn 1MB.

2. Máy chủ ứng dụng được cấu hình kém

Bạn gặp lỗi HTTP 413 vì yêu cầu máy khách vượt quá giới hạn kích thước được xác định trong cấu hình máy chủ ứng dụng của bạn. Ví dụ: ứng dụng Express trên máy chủ Node.js giới hạn nội dung yêu cầu JSON ở 100Kb theo mặc định. Do đó, nếu bạn không định cấu hình Express để mong đợi một giá trị lớn hơn một cách rõ ràng, bạn sẽ gặp lỗi HTTP 413 cho bất kỳ yêu cầu JSON nào lớn hơn 100Kb.

Trong bài viết này, bạn sẽ tìm hiểu cách giải quyết lỗi HTPP 413 do nguyên nhân thứ hai, cụ thể là máy chủ ứng dụng bị cấu hình sai. Nếu bạn muốn đi sâu tìm hiểu nguyên nhân thứ hai, hãy xem bài viết này .

Sửa lỗi “413 Đối tượng yêu cầu quá lớn” trong Express

Để khắc phục lỗi “413 Đối tượng Yêu cầu Quá lớn” trong ứng dụng Express, bạn chỉ phải cập nhật tệp khởi tạo máy chủ. Đây thường được gọi là index.jshoặc server.jsvà là nơi bạn khởi tạo máy chủ Express. Đảm bảo rằng tệp này chứa các dòng sau:

// index.js or server.js

const express = require("express")

// ...
    
const app = express()

// ...

// fixing "413 Request Entity Too Large" errors
app.use(express.json({limit: "10mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))

// ...

Hai dòng mã cuối cùng này mở rộng kích thước của tải trọng JSON và các tham số truy vấn URL lên 10MB. Điều này là đủ để tránh hầu hết các lỗi "413 Đối tượng Yêu cầu Quá lớn" trên ứng dụng Express của bạn. Định cấu hình hai giá trị giới hạn theo nhu cầu của bạn, nhưng không làm quá khổ chúng một cách không cần thiết.

Et voilà! Bạn vừa học được cách giải quyết lỗi “413 Đối tượng Yêu cầu Quá lớn” trên ứng dụng Node.js Express.

 

Sự kết luận

Trong bài viết này, bạn đã biết lỗi HTTP 413 là gì, tại sao nó xảy ra và cách giải quyết lỗi. Cụ thể, bạn đã thấy cách sửa lỗi “Đối tượng yêu cầu 413 Quá lớn” trên máy chủ Node.js Express. Đây là một vấn đề đặc biệt phổ biến xảy ra khi yêu cầu máy khách lớn hơn máy chủ mong đợi. Như được hiển thị, chỉ mất một vài dòng mã để giải quyết nó.

Cảm ơn vì đã đọc! Tôi hy vọng rằng bạn thấy bài viết này hữu ích. Hãy để lại bất kỳ câu hỏi, nhận xét hoặc đề xuất.

Nguồn: https://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

Cách Khắc Phục Lỗi “413 Đối Tượng Yêu Cầu Quá Lớn” Trong Node.js

Node.js の「413 Request Entity Too Large」エラーを修正する方法

最近、「413 Request Entity Too Large」Express エラーに対処する必要がありました。いくつかの調査の後、これは 2 つの一般的な理由で発生する可能性があるかなり一般的な問題であることがわかりました。どちらの場合も、クライアントが大きすぎると見なされる要求を行うと、サーバーによってエラーがスローされます。

「413 Request Entity Too Large」エラーについて知っておくべきことをすべて学び、Express でそれを修正する方法を見てみましょう。

 

「413 Request Entity Too Large」エラーとは何ですか?

MDNで説明されているように、HTTP413 Payload Too Large応答ステータス コードは、クライアントによって実行された要求エンティティがサーバーによって定義された制限よりも大きいことを示します。この結果、サーバーは接続を閉じるか、Retry-Afterヘッダー フィールドを返す可能性があります。

HTTP413 Payload Too Large以前は と呼ばれてい413 Request Entity Too Largeました。ほとんどのシステムは今でもそのように呼んでいることに注意してください。413 Payload Too Largeそのため、「Request Entity Too Large」というエラー メッセージが表示された場合は、HTTPエラーを処理していると推測できます。

 

HTTP エラー 413 が発生するのはなぜですか?

前に説明したように、HTTP エラー 413 は、クライアントの要求がサーバーが処理しようとしている、または処理できるよりも大きい場合に発生します。具体的には、これは 2 つの理由で発生する可能性があります。それらを掘り下げてみましょう。

1. 不適切に構成された Web サーバー

クライアント要求が Web サーバー構成で定義されたサイズ制限を超えているため、HTTP エラー 413 が発生します。たとえば、デフォルトで Nginx によって課されるクライアント リクエストのサイズ制限は 1 MB に設定されています。したがって、より大きな値を明示的に予期するように Nginx を構成しない場合、1 MB を超えるすべての要求に対して HTTP エラー 413 が発生します。

2. アプリケーション サーバーの構成が不十分

クライアント要求がアプリケーション サーバー構成で定義されたサイズ制限を超えているため、HTTP エラー 413 が発生します。たとえば、Node.js サーバー上の Express アプリケーションは、JSON 要求本文をデフォルトで 100Kb に制限します。したがって、Express がより大きな値を明示的に期待するように構成しない場合、100Kb を超える JSON 要求に対して HTTP エラー 413 が発生します。

この記事では、2 番目の原因、つまり不適切な構成のアプリケーション サーバーによって引き起こされる HTPP 413 エラーに対処する方法を学習します。2 つ目の原因について詳しく知りたい場合は、この記事をご覧ください。

Express での「413 Request Entity Too Large」エラーの修正

Express アプリケーションの「413 Request Entity Too Large」エラーを修正するには、サーバー初期化ファイルを更新するだけです。これは一般にindex.jsor server.jsand と呼ばれ、Express サーバーを初期化する場所です。このファイルに次の行が含まれていることを確認してください。

// index.js or server.js

const express = require("express")

// ...
    
const app = express()

// ...

// fixing "413 Request Entity Too Large" errors
app.use(express.json({limit: "10mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))

// ...

これらの最後の 2 行のコードにより、JSON ペイロードと URL クエリ パラメータのサイズが 10MB に拡張されます。Express アプリケーションでの「413 Request Entity Too Large」エラーのほとんどを回避するには、これで十分です。必要に応じて 2 つの制限値を構成しますが、不必要に大きくしないでください。

ほら!Node.js Express アプリケーションの「413 Request Entity Too Large」エラーを解決する方法を学習しました。

 

結論

この記事では、HTTP エラー 413 とは何か、それが発生する理由、およびその対処方法について説明しました。具体的には、Node.js Express サーバーで「413 Request Entity Too Large」を修正する方法を見てきました。これは、クライアントの要求がサーバーの予想よりも大きい場合に発生する特に一般的な問題です。示されているように、それを解決するには数行のコードしか必要ありません。

読んでくれてありがとう!この記事がお役に立てば幸いです。ご質問、ご意見、ご提案がございましたら、お気軽にお寄せください。

ソース: https://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

Node.js の「413 Request Entity Too Large」エラーを修正する方法
Thierry  Perret

Thierry Perret

1661556600

Réparer L'erreur "413 Request Entity too Large" Dans Node.js

J'ai récemment dû faire face à l'erreur Express "413 Request Entity Too Large". Après quelques recherches, j'ai découvert qu'il s'agit d'un problème assez courant qui peut survenir pour deux raisons générales. Dans les deux cas, l'erreur est levée par le serveur lorsqu'un client fait une requête considérée comme trop volumineuse.

Apprenons maintenant tout ce que vous devez savoir sur l'erreur "413 Request Entity Too Large" et voyons comment la corriger dans Express.

 

Qu'est-ce que l'erreur « 413 Request Entity Too Large » ?

Comme expliqué dans MDN , le code d'état de la réponse HTTP 413 Payload Too Largeindique que l'entité de requête effectuée par le client est supérieure aux limites définies par le serveur. Par conséquent, le serveur peut fermer la connexion ou renvoyer un Retry-Afterchamp d'en-tête.

HTTP 413 Payload Too Larges'appelait auparavant413 Request Entity Too Large . Notez que la plupart des systèmes l'appellent encore ainsi. Par conséquent, si vous rencontrez un message d'erreur "Request Entity Too Large", vous pouvez supposer que vous avez affaire à une 413 Payload Too Largeerreur HTTP.

 

Pourquoi l'erreur HTTP 413 se produit-elle ?

Comme expliqué précédemment, une erreur HTTP 413 se produit lorsque la demande du client est supérieure à ce que le serveur souhaite ou peut traiter. Plus précisément, cela peut se produire pour deux raisons. Creusons-les.

1. Serveur Web mal configuré

Vous obtenez une erreur HTTP 413 car la demande du client dépasse la limite de taille définie dans la configuration de votre serveur Web. Par exemple, la taille limite de la demande client imposée par Nginx par défaut est définie sur 1 Mo . Par conséquent, si vous ne configurez pas Nginx pour attendre explicitement une valeur plus grande, vous obtiendrez une erreur HTTP 413 pour toute requête supérieure à 1 Mo.

2. Serveur d'applications mal configuré

Vous obtenez une erreur HTTP 413 car la demande du client dépasse la limite de taille définie dans la configuration de votre serveur d'applications. Par exemple, une application Express sur un serveur Node.js limite le corps de la requête JSON à 100 Ko par défaut. Par conséquent, si vous ne configurez pas Express pour attendre explicitement une valeur plus élevée, vous obtiendrez une erreur HTTP 413 pour toute requête JSON supérieure à 100 Ko.

Dans cet article, vous apprendrez à résoudre les erreurs HTTP 413 causées par la deuxième cause, à savoir un serveur d'application mal configuré. Si vous souhaitez vous plonger dans la seconde cause, consultez cet article .

Correction de l'erreur "413 Request Entity Too Large" dans Express

Pour corriger l'erreur "413 Request Entity Too Large" dans une application Express, il vous suffit de mettre à jour le fichier d'initialisation du serveur. C'est généralement appelé index.jsou server.jset c'est là que vous initialisez le serveur Express. Assurez-vous que ce fichier contient les lignes suivantes :

// index.js or server.js

const express = require("express")

// ...
    
const app = express()

// ...

// fixing "413 Request Entity Too Large" errors
app.use(express.json({limit: "10mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))

// ...

Ces deux dernières lignes de code étendent la taille de la charge utile JSON et des paramètres de requête d'URL à 10 Mo. Cela devrait être suffisant pour éviter la plupart des erreurs "413 Request Entity Too Large" sur votre application Express. Configurez les deux valeurs limites selon vos besoins, mais sans les surdimensionner inutilement.

Et voilà! Vous venez d'apprendre comment résoudre l'erreur "413 Request Entity Too Large" sur une application Node.js Express.

 

Conclusion

Dans cet article, vous avez appris ce qu'est une erreur HTTP 413, pourquoi elle se produit et comment y remédier. Plus précisément, vous avez vu comment réparer le "413 Request Entity Too Large" sur un serveur Node.js Express. Il s'agit d'un problème particulièrement courant qui se produit lorsque la demande du client est supérieure à ce que le serveur attend. Comme indiqué, il suffit de quelques lignes de code pour le résoudre.

Merci d'avoir lu! J'espère que vous avez trouvé cet article utile. N'hésitez pas à laisser des questions, des commentaires ou des suggestions.

Source : https://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

Réparer L'erreur "413 Request Entity too Large" Dans Node.js
黎 飞

黎 飞

1661554800

如何修复 Node.js 中的“413 请求实体太大”错误

我最近不得不处理“413 Request Entity Too Large” Express 错误。经过一番研究,我发现这是一个相当普遍的问题,通常有两个原因。在这两种情况下,当客户端发出的请求被认为太大时,服务器都会抛出错误。

现在让我们了解您需要了解的有关“413 Request Entity Too Large”错误的所有信息,并了解如何在 Express 中修复它。

 

什么是“413 请求实体太大”错误?

正如MDN中所解释的,HTTP413 Payload Too Large响应状态码表明客户端执行的请求实体大于服务器定义的限制。因此,服务器可能会关闭连接或返回Retry-After标头字段。

HTTP413 Payload Too Large以前称为413 Request Entity Too Large. 请注意,大多数系统仍然这样称呼它。因此,如果您遇到“请求实体太大”错误消息,您可以假设您正在处理 HTTP413 Payload Too Large错误。

 

为什么会出现 HTTP 错误 413?

如前所述,当客户端请求大于服务器愿意或能够处理时,会发生 HTTP 错误 413。具体来说,这可能由于两个原因而发生。让我们深入研究一下。

1. 配置不当的 Web 服务器

您收到 HTTP 错误 413,因为客户端请求超出了 Web 服务器配置中定义的大小限制。例如,默认情况下 Nginx 施加的客户端请求大小限制设置为 1 MB。因此,如果您没有将 Nginx 配置为显式地期望更大的值,那么对于任何大于 1MB 的请求,您都会收到 HTTP 错误 413。

2. 配置不当的应用服务器

您收到 HTTP 错误 413,因为客户端请求超出了应用程序服务器配置中定义的大小限制。例如,Node.js 服务器上的 Express 应用程序默认将 JSON 请求正文限制为 100Kb。因此,如果您没有将 Express 配置为明确期望更大的值,那么对于任何大于 100Kb 的 JSON 请求,您都会收到 HTTP 错误 413。

在本文中,您将学习如何解决由第二个原因导致的 HTPP 413 错误,即配置错误的应用程序服务器。如果您想深入研究第二个原因,请查看这篇文章

修复 Express 中的“413 请求实体太大”错误

要修复 Express 应用程序中的“413 Request Entity Too Large”错误,您只需更新服务器初始化文件。这通常称为index.jsor server.js,是您初始化 Express 服务器的地方。确保此文件包含以下行:

// index.js or server.js

const express = require("express")

// ...
    
const app = express()

// ...

// fixing "413 Request Entity Too Large" errors
app.use(express.json({limit: "10mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))

// ...

最后两行代码将 JSON 有效负载和 URL 查询参数的大小扩展到 10MB。这应该足以避免您的 Express 应用程序中出现大多数“413 Request Entity Too Large”错误。根据您的需要配置这两个限制值,但不要不必要地过大。

瞧!您刚刚学习了如何解决 Node.js Express 应用程序上的“413 Request Entity Too Large”错误。

 

结论

在本文中,您了解了 HTTP 错误 413 是什么、它发生的原因以及如何解决它。具体来说,您看到了如何在 Node.js Express 服务器上修复“413 Request Entity Too Large”。当客户端请求大于服务器预期时,这是一个特别常见的问题。如图所示,只需几行代码即可解决。

谢谢阅读!我希望你觉得这篇文章有帮助。随时留下任何问题、意见或建议。

来源:https ://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

如何修复 Node.js 中的“413 请求实体太大”错误

How to Fix “413 Request Entity Too Large” Error in Node.js

I recently had to deal with the “413 Request Entity Too Large” Express error. After some research, I found out that this is a fairly common problem that can occur for two general reasons. In both cases, the error is thrown by the server when a client makes a request that is considered too large.

Let’s now learn everything you need to know about the “413 Request Entity Too Large” error and see how to fix it in Express.

See more at: https://javascript.plainenglish.io/how-to-fix-413-request-entity-too-large-error-in-node-js-226c0070e4f4

#nestjs #express 

How to Fix “413 Request Entity Too Large” Error in Node.js

Express-gateway: A Microservices API Gateway Built on top Of Express

A Microservices API Gateway Built Using Express.js and Express Middleware


Express Gateway

DEPRECATION NOTICE This Project is no longer maintained. Read here for more details or if you're interested in taking over that project.

Express Gateway is a microservices API gateway that sits at the heart of any microservices or serverless architecture, regardless of what language or platform you're using.

Express Gateway secures your microservices and serverless functions and expose them through APIs using Node.js, Express and Express middleware.

Developing cloud native applications, orchestrating and managing them now can be done insanely fast all on one seamless platform without having to introduce additional infrastructure.


Website   Getting Started   Docs


Main Features

  • Microservices and Serverless QoS Proxy and Security
  • Built Entirely on JavaScript/Node.js using Express and Express Middleware
  • Dynamic Centralized Config
  • API Consumer and Credentials Management
  • Plugins and Plugin Framework
  • Distributed Data Store
  • CLI
  • REST API
  • Cloud Native Execution

Installation

If you have Node.js already installed:

# install Express Gateway
$ npm install -g express-gateway

Creating a Gateway

# create a new gateway using the CLI
$ eg gateway create

Get Help

Need help or have a question?

Community

Express has a community that we hope to extend further with Express Gateway's gateway use case for Express and its middleware.

Roadmap

The Express Gateway roadmap consists of three parts:

  1. FeatHub - features requested and voted on by any community member, this feeds into the...
  2. Roadmap - the published roadmap of all features under considerations and projected timeframes, the highest priority items are put into the...
  3. Waffle board - a real time as a public task board on Waffle.io with backlog of stories for the next release

LTS Policy

Module VersionRelease DateMinimum EOLEOL WithStatus
1.x.xJul 2016Dec 2019Node 8Current

Contribution

All contributions welcome! Please see the contributor's guide

Download Details:

Author: ExpressGateway
Source Code: https://github.com/ExpressGateway/express-gateway 
License: Apache-2.0 license

#javascript #express #microservices 

Express-gateway: A Microservices API Gateway Built on top Of Express

Count & Limit Requests By Key with Atomic increments

node-rate-limiter-flexible

rate-limiter-flexible counts and limits number of actions by key and protects from DDoS and brute force attacks at any scale.

It works with Redis, process Memory, Cluster or PM2, Memcached, MongoDB, MySQL, PostgreSQL and allows to control requests rate in single process or distributed environment.

Atomic increments. All operations in memory or distributed environment use atomic increments against race conditions.

Traffic bursts. Replace Token Bucket with BurstyRateLimiter

Fast. Average request takes 0.7ms in Cluster and 2.5ms in Distributed application. See benchmarks.

Flexible. Combine limiters, block key for some duration, delay actions, manage failover with insurance options, configure smart key blocking in memory and many others.

Ready for growth. It provides unified API for all limiters. Whenever your application grows, it is ready. Prepare your limiters in minutes.

Friendly. No matter which node package you prefer: redis or ioredis, sequelize/typeorm or knex, memcached, native driver or mongoose. It works with all of them.

In memory blocks. Avoid extra requests to store with inmemoryBlockOnConsumed.

Deno compatible See this example

It uses fixed window as it is much faster than rolling window. See comparative benchmarks with other libraries here

Installation

npm i --save rate-limiter-flexible

yarn add rate-limiter-flexible

Basic Example

Points can be consumed by IP address, user ID, authorisation token, API route or any other string.

const opts = {
  points: 6, // 6 points
  duration: 1, // Per second
};

const rateLimiter = new RateLimiterMemory(opts);

rateLimiter.consume(remoteAddress, 2) // consume 2 points
    .then((rateLimiterRes) => {
      // 2 points consumed
    })
    .catch((rateLimiterRes) => {
      // Not enough points to consume
    });

RateLimiterRes object

Both Promise resolve and reject return object of RateLimiterRes class if there is no any error. Object attributes:

RateLimiterRes = {
    msBeforeNext: 250, // Number of milliseconds before next action can be done
    remainingPoints: 0, // Number of remaining points in current duration 
    consumedPoints: 5, // Number of consumed points in current duration 
    isFirstInDuration: false, // action is first in current duration 
}

You may want to set next HTTP headers to response:

const headers = {
  "Retry-After": rateLimiterRes.msBeforeNext / 1000,
  "X-RateLimit-Limit": opts.points,
  "X-RateLimit-Remaining": rateLimiterRes.remainingPoints,
  "X-RateLimit-Reset": new Date(Date.now() + rateLimiterRes.msBeforeNext)
}

Advantages:

Middlewares, plugins and other packages

Some copy/paste examples on Wiki:

Migration from other packages

  • express-brute Bonus: race conditions fixed, prod deps removed
  • limiter Bonus: multi-server support, respects queue order, native promises

Docs and Examples

Changelog

See releases for detailed changelog.

Basic Options

points

Default: 4

Maximum number of points can be consumed over duration

duration

Default: 1

Number of seconds before consumed points are reset.

Never reset points, if duration is set to 0.

storeClient

Required for store limiters

Have to be redis, ioredis, memcached, mongodb, pg, mysql2, mysql or any other related pool or connection.

Other options on Wiki:

Smooth out traffic picks:

Specific:

API

Read detailed description on Wiki.

Benchmark

Average latency during test pure NodeJS endpoint in cluster of 4 workers with everything set up on one server.

1000 concurrent clients with maximum 2000 requests per sec during 30 seconds.

1. Memory     0.34 ms
2. Cluster    0.69 ms
3. Redis      2.45 ms
4. Memcached  3.89 ms
5. Mongo      4.75 ms

500 concurrent clients with maximum 1000 req per sec during 30 seconds

6. PostgreSQL 7.48 ms (with connection pool max 100)
7. MySQL     14.59 ms (with connection pool 100)

Note, you can speed up limiters with inmemoryBlockOnConsumed option.

Contribution

Appreciated, feel free!

Make sure you've launched npm run eslint before creating PR, all errors have to be fixed.

You can try to run npm run eslint-fix to fix some issues.

Any new limiter with storage have to be extended from RateLimiterStoreAbstract. It has to implement 4 methods:

  • _getRateLimiterRes parses raw data from store to RateLimiterRes object.
  • _upsert must be atomic. it inserts or updates value by key and returns raw data. it must support forceExpire mode to overwrite key expiration time.
  • _get returns raw data by key or null if there is no key.
  • _delete deletes all key related data and returns true on deleted, false if key is not found.

All other methods depends on store. See RateLimiterRedis or RateLimiterPostgres for example.

Note: all changes should be covered by tests.

Download Details:

Author: Animir
Source Code: https://github.com/animir/node-rate-limiter-flexible 
License: ISC license

#javascript #node #security #express 

Count & Limit Requests By Key with Atomic increments