The payload from the Axios POST request is failing to reach its destination endpoint

I have two Express servers up and running - a gateway and an authentication service. I am facing an issue where the payload I set in the body of a request from my gateway to the authentication server never seems to arrive, despite there being no apparent CORS problems. Interestingly, when I try the same request using Postman, everything works fine. The code for the controller in my authentication service is as follows:

authentication-service controller

export const post = async (req: Request, res: Response): Promise<Response> => {
  const newUser = req.body;

  if (newUser.email === undefined || newUser.password === undefined) {
    log.debug(newUser);
    log.debug('Email and password were not defined');
    return res.sendStatus(400);
  } else {
    return res.sendStatus(200);
  }
}

gateway

const data = new FormInfo();
  data.append('email', 'test');
  data.append('password', 'test');

  console.log(data);

  const registerRes = await axios({
    method: 'post',
    url: process.env.REGISTER_USER_URL,
    headers: {
      ...data.getHeaders(),
    },
    data,
  })
      .then((response: any) => response)
      .catch((error) => error.response);

I've been troubleshooting this issue for days now, but haven't been able to identify what's going wrong. Any insights on where I might be making a mistake?

I have attempted disabling CORS.

I have also tried enabling CORS using the following approach:

const whitelist = ['http://localhost:3000'];

      const corsOptions = {
        credentials: true,
        origin: (origin: any, callback: any) => {
          if (whitelist.indexOf(origin) !== -1) {
            callback(null, true);
          } else {
            callback(new Error('Not allowed by CORS'));
          }
        },
      };

app.use(cors(corsOptions));

The current configuration for CORS is like this:

app.use(cors());

Answer №1

After some experimentation, I was able to resolve the issue by switching from FormInfo to qs. If anyone has insights on why this change worked, please share so I can make adjustments to my solution.

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

Deactivate the chosen tab by clicking the Mat-Tab button

I was trying to implement a way to disable the selected mat-tab and its elements when a button is clicked, //HTML <mat-tab-group #tabGroup> <mat-tab *ngFor="let subject of subjects" [label]="subject.name"> {{ subject.name }} ...

React with TypeScript - Troubleshooting TS Error when Iterating over List Item (LI) Elements

Iterating through a group of <li> elements to strip away a specific class, then applying the same class to a different <li>. See the snippet below: useEffect(() => { if (dnArrowIdx === undefined) { const allLi = Array.from(document. ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

Jasmine encountered an error while trying to compare the same string: 'Expected the values to match.'

I'm encountering an error message, despite verifying that the strings are identical: Expected { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'ty ...

NextJS introduces a unique functionality to Typescript's non-null assertion behavior

As per the typescript definition, the use of the non-null assertion operator is not supposed to impact execution. However, I have encountered a scenario where it does. I have been struggling to replicate this issue in a simpler project. In my current proj ...

Discover the best practices for implementing services within the import decorator of an angular module configuration

Is there a way to access a service inside the load module in Angular, especially when the module is loaded from a decorator and the service is not yet DI? You can refer to this answer for an example. For instance, if the method in the service returns an ...

Using the timer function to extract data within a specific time frame - a step-by-step guide

Is there anything else I need to consider when the temperature increases by 1 degree? My plan is to extract data from my machine for the last 30 seconds and then send it to my database. set interval(function x(){ If(current_temp != prev_temp){ if((c ...

Navigating the translation URL in a Node.js Express app

Can someone please guide me on how to handle routing for translated URLs in a Node.js Express application? In my app.js file, I currently have the following routes. How can I improve this setup for handling URLs that change based on language, while still ...

Having an issue where the Material Angular 6 DatePicker is consistently displaying my selected date as one day earlier

I've encountered a strange issue with the current version of the Material Angular DatePicker. After upgrading from A5 to A6, it started to parse my date one day earlier than expected. You can see an example of this problem here: https://stackblitz.com ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

The initial res.body object in NodeJS is enclosed in quotation marks

I've hit a roadblock while working on my social media website project using the MERN stack. Despite scouring the internet, I haven't been able to find a solution to the issue at hand. While following an online course, I encountered a problem tha ...

Browsing data privacy is crucial, which is why I have decided to operate both servers on the same port to ensure that cookies are

In my project, the front end is built with Next.js and the backend uses Express and Node.js. These projects are currently running on different ports - the frontend on port 3000 and the backend on port 8080. While everything works fine locally and cookies a ...

Transferring binary data with Node.js

I am currently utilizing Flash to capture and upload audio to a node server. The Flash client I am using is a modified version of jrecorder. After the user finishes recording, the audio is sent via a POST request (not through a form due to Flash limitation ...

What is the process for converting a buffer into an image file?

I am struggling with retrieving images stored in GridFS and converting them into a buffer using the code I have written. However, I'm unable to find proper documentation on how to render an image from this buffer within the MEAN stack environment. My ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

When attempting to deploy the app on Heroku, I encountered an unexpected Internal Server Error

My journey into developing my first application began by following a tutorial for Mongo / Express / Node. The app worked flawlessly on localhost port:3000 when running the nodemon server.js. However, when I tried to connect GitHub with Heroku, I kept rece ...