Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page:

const app = express();

// part A
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded());

app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);

Everything is running smoothly so far.

Now, I have another controller that specifically deals with RAW DATA:

// part B
const concat = require('concat-stream');
app.use(function(req, res, next) {
  req.pipe(concat(function(data: any) {
    req.body = data;
    next();
  }));
});

app.post('*', otherController.post);

export let post = (req: any, res: Response) => {
  console.log(req.body); //I can view the RAW DATA here
  res.end('n');
}

Both sections function correctly on their own. However, when combined, the second section ceases to work properly.

Is there a way for me to specify that the req.pipe should only be used for part B?

Answer №1

This particular middleware, like most others in existence, lacks a built-in feature for excluding it from specific requests. The reason being that users may want to exclude it based on various criteria such as URL, headers, query strings, user data, and more. Therefore, the responsibility of determining whether or not the middleware should be applied falls on your shoulders: you can either (a) explicitly include it by defining its usage in the routes as per our documentation recommendations, or (b) create your own exclusion logic by wrapping the middleware with a custom function:

const parseExtend = bodyParser.urlencoded({ extended: true });
app.use((req, res, next) => shouldParseRequest(req) ? parseExtend(req, res, next) : next());

/* Define your custom shouldParseRequest function to determine when the middleware should not parse JSON */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When you try to import a component, it may result in a blank page displaying an error message stating: "TypeError: Cannot set property 'components'

One interesting feature is the Vue component named DisplayContent, <template> <div></div> </template> <script lang="ts"> import { Vue, Component } from "vue-property-decorator"; import Home from "@/ ...

The HTML table seems to be inexplicably replicating defaultValue values

I'm encountering an issue where, when I use JavaScript to add a new table data cell (td), it ends up copying the defaultValue and innerText of the previous td in the new cell. This is confusing to me because I am simply adding a new HTML element that ...

angularjs .reject not executing correctly within the then statement

I'm having trouble identifying the bug in my code. For some reason, $q.defer().reject() isn't functioning correctly. defer.resolve works as expected and even reaches the finally segment, but defer.reject (although it doesn't throw an error) ...

Adding a hash to asset paths in NextJS static builds

After running next build && next export, I receive a directory named out, which is great. When examining the source code, such as in the index.html file, it requests assets from <link rel="preload" href="/_next/static/css/styles.aa216922.chunk. ...

Babel not functioning properly with static class property

I'm utilizing JSDOC along with all its supported npm plugins to generate comprehensive documentation. However, I've been facing difficulties when running jsdoc and parsing JSX files, as it consistently throws an error near the "=" sign as shown b ...

Once all routes have been registered, the Express.Router middleware will be activated for each route

Currently, I am working on a straightforward application that includes a login page and a special section accessible only to authenticated users. In case unauthenticated users attempt to access restricted areas, they are redirected back to the login page. ...

Recurrence of solely the middle segment of the separator's background picture

I have a unique divider image with fading top and bottom parts. I'm wondering if it's possible to use a sprite and 3 divs to only repeat the middle section, considering that my height is variable. Do I need separate images for the top, middle, an ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing. const createNewUser = (data) => { return new Promise(async (resolve, ...

Displaying the contents of a local HTML file in a div

I am attempting to load a local HTML file into a div, however it is not displaying any content on the page despite showing an alert. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> ...

Steps to integrate the Save as PNG functionality in Vega using a customized menu

As I develop a data dashboard with Vega for visualizing outputs, I decided to customize the menu system by removing the actions dropdown. However, I still want to incorporate the "Save as PNG" option from the original dropdown (as shown in the image below) ...

Data is being stored in a fresh record rather than being saved within an array

I'm currently working with the MEAN stack and using the Multer module for uploading images. While I am able to successfully retrieve images from Angular and post image paths to a Mongoose collection, I am encountering an issue. Instead of receiving ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

Node.js server-side storage solutions for integration with Dojo

Currently, I am working on developing a new application. It is my first time creating a single-page AJAX application that solely relies on Restful stores. So far, I have written some code and executed simple queries using the GET method. To maintain organ ...

The Carousel feature functions properly with 3 or more slides, but malfunctions when there are only 2 slides present

After implementing a minimal carousel, I discovered that it functions perfectly with 3 or more slides. However, as soon as I remove some slides, issues start to arise. Some of the problems I encountered include: The sliding animation is removed on ' ...

What is the process for delivering a binary output using AWS Lambda in Node.js through API Gateway?

My goal is to create a Lambda function and API Gateway that retrieves an image file from an s3 bucket and outputs it directly as a response. Eventually, I want to be able to resize images on the fly without saving them back to s3. However, I am encounterin ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

initiate a click event within another click event

This is an HTML Code snippet: <ul id="linkjess"> <li><a href="javascript:setfolder('medewerkers', '1000');">medewerkers 1000</a></li> <li><a href="javascript:setfolder('medewerkers', ...

Issue encountered while executing Mongoose update function in the router.patch() method

I encountered an issue while trying to update a product on a cloud-based mongoose database using router.patch(). I am simulating the update process with Postman, but I keep receiving an error that says "req.body[Symbol.iterator] is not a function." Below i ...