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

Request with an HTTP header for authentication

Here's a straightforward question that may seem simple to some developers but could be tricky for beginners. So, my question is - how can I send an HTTP request from a browser when a user clicks a button and also add an authorization header to the re ...

"Modifying the form of an item by adjusting its variable, and rendering certain object properties as

let myObj = { a: { value: 1 }, b: { value: 2 } } myObj = { // How can I make the property b optional in myObj without specifying my own type? a: { value: 123 } } Is there a way to make the property myObj.b ...

`There seems to be a problem as the .then function is

I am currently working with Node.js Express and encountering an error when calling a model from the controller. I'm receiving a Type Error stating that .then is undefined. Below is the code snippet I have been using. Can someone please assist me in id ...

Building Surveys with NodeJS and SurveyMonkey API

I have set up a small server using NodeJS/Express and incorporated node-fetch to communicate with SurveyMonkey's API. At present, I can see two surveys on my account by utilizing their Postman collection. However, when I attempt to utilize my custom e ...

Displaying the default value in a Material-UI v5 select component

I am looking to display the default value in case nothing has been selected yet for the mui v5 select component below, but currently it appears empty... <StyledCustomDataSelect variant='outlined' labelId='demo-simple- ...

The Nest interceptor seems to be malfunctioning when used with asynchronous methods

I have a requirement to track the IP address and hit count for a specific API, so I created an interceptor that logs this information (Before...) to the console without any errors and continues with the API functionality. I even tested hitting the API with ...

Incorporating responsive design with React and Typescript

Trying to utilize React with TypeScript, I aim to dynamically generate components based on a field name // Storing all available components const components = { ComponentA, ComponentB, }; // Dynamically render the component based on fieldName const di ...

Retrieving a function from a JavaScript file located in a publicly accessible directory

Having trouble accessing a function from the JS file scripts.js within the public folder where my CSS file is also located. Despite following various tutorials like this, I keep encountering the error message Error: Cannot find module './scripts.js&ap ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

Loading custom components dynamically in Angular with SVG: a how-to guide

Looking for a way to dynamically load SVG items with ease. The items needed are quite simple. Here's a basic template: <svg:rect [attr.x]="x" [attr.y]="y" width="10" height="10" /> Component Class Example: export class DraggableSvgItemCompon ...

Executing next middleware after redirection in Express.js

I am attempting to analyze the impact of integration tests on an Express.js middleware in order to influence behavior. A peculiar situation has arisen where the behavior of Express within the application is not easily predictable (at least not by me). For ...

Utilize a fresh function in Angular to retrieve and store data from a URL into a variable

Currently, I am attempting to utilize Angular in order to retrieve data from a link upon clicking a button. As a newcomer to Angular with only 2 days experience, my knowledge is quite limited. What I aim to achieve is triggering the loading of JSON data w ...

The issue of CORS not functioning properly has been encountered in a Cordova application connected to an Express

Running a Cordova app in the browser and attempting to fetch data using the Fetch API from a server running on a different port (Express). CORS has been allowed: app.options('*', (req, res) => { res.header('Access-Control-Allow-Origi ...

What is the reasoning behind TypeScript allowing the reading of an undefined variable within a closure?

While exploring, I came across this detail that seems undocumented. Here's some legitimate TypeScript code that results in undefined being output: let x: number; const f= () => { const y= x; console.log(y); } f(); Playground Within the fu ...

How does Node.js differ from incorporating a framework such as Express.js?

Coming from a networking background, I am venturing into the world of web development and eager to explore Node.js along with other modern web technologies. Can someone explain the distinctions between utilizing plain "stock" Node.js versus incorporating ...

How to make a token expire in Node.js Express?

I'm currently developing a Node.JS project using express. One of the features I need to implement is sending password reset emails to users with a jwt token that expires after 15 minutes. My concern is how to force-expire the token if a user changes t ...

The projection of state in NGRX Store.select is not accurately reflected

Every time I run the following code: valueToDisplay$ =store.select('model','sub-model') The value stored in valueToDisplay$ always corresponds to 'model'. Despite trying various approaches to properly project the state, it s ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

Optimal Approach for Building REST APIs with Node.js

Having a background in .Net and C#, I am now venturing into the world of Node.js for a project involving MongoDB. The data from various tools is stored in different collections within MongoDB, and my task is to create REST APIs using Node.js to perform CRU ...