Axios Error: Header content contains an invalid character ['adapter']

Here is a code snippet that highlights the problem:

import axios, { AxiosRequestConfig } from "axios";

function combineRequestParams(defaultParams: AxiosRequestConfig, params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
  return {
    ...defaultParams,
    ...params1,
    ...(params2 || {}),
    headers: {
      ...defaultParams,
      ...(params1.headers || {}),
      ...((params2 && params2.headers) || {}),
    },
  };
}

(async () => {
  try {

    const client = axios.create({

      transformRequest: [(data, headers) => { return data; }],   // Omitting this line causes: Invalid character in header content ["transformRequest"] 
      transformResponse: [(data, headers) => { return data; }], // Not including this line results in: Invalid character in header content ["transformResponse"] 

      baseURL: "https://localhost:7001/",
    });

    const requestParams = combineRequestParams(client.defaults, {}, {})

    client.request({
      ...requestParams,
      headers: {
        "Content-Type": "application/json",
        ...requestParams.headers,
      },
      params: {date:'2020-03-31'},
      responseType: 'json',
      url: '/overview',
    });

  } catch (error) {
    console.log(error);
  }
})();

The error message you may encounter is:

(node:60845) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["adapter"]
    at ClientRequest.setHeader (_http_outgoing.js:529:3)
    at new ClientRequest (_http_client.js:241:14)
    at Object.request (https.js:314:10)
    at RedirectableRequest._performRequest (/Users/kamz/workspace/clarity/clarity-model/node_modules/follow-redirects/index.js:262:24)
    at new RedirectableRequest (/Users/kamz/workspace/clarity/clarity-model/node_modules/follow-redirects/index.js:60:8)
    at Object.request (/Users/kamz/workspace/clarity/clarity-model/node_modules/follow-redirects/index.js:458:14)
    at dispatchHttpRequest (/Users/kamz/workspace/clarity/clarity-model/node_modules/axios/lib/adapters/http.js:195:25)
    at new Promise (<anonymous>)
    at httpAdapter (/Users/kamz/workspace/clarity/clarity-model/node_modules/axios/lib/adapters/http.js:46:10)
    at dispatchRequest (/Users/kamz/workspace/clarity/clarity-model/node_modules/axios/lib/core/dispatchRequest.js:52:10)
(node:60845) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:60845) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Answer №1

Your mergeRequestParams function has an error in the way it handles headers. Instead of spreading ...defaultParams in the headers, you should spread ...defaultParams.headers.

You can actually spread undefined, so you can simplify the code like this:

function mergeRequestParams(defaultParams: AxiosRequestConfig, params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
  return {
    ...defaultParams,
    ...params1,
    ...params2,
    headers: {
      ...defaultParams.headers,
      ...params1.headers,
      ...params2?.headers,
    },
  };
}

In my opinion, it would be more efficient to create a separate function that combines two configurations and use it as a callback for Array.reduce to combine multiple configurations.

function mergeTwoParams(params1: AxiosRequestConfig, params2: AxiosRequestConfig): AxiosRequestConfig {
  return {
    ...params1,
    ...params2,
    headers: {
      ...params1.headers,
      ...params2.headers,
    },
  };
}

function mergeRequestParams(...params: AxiosRequestConfig[]): AxiosRequestConfig {
  return params.reduce(mergeTwoParams, {}); // initial value is only needed to prevent error when calling with 0 configs
}

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

What is the best way to restrict the return type of a function depending on the argument value?

Is there a way to consolidate the methods of an interface into a single function with an additional operation parameter? Despite being able to call the resulting function as expected, I'm struggling to narrow the return type within the function itself ...

Unexpected character error occurs when using VSCode with Vue: ''‌'

Recently, I've encountered some strange errors while working on a Vuejs project in VSCode. Whenever I try to write arrow functions or use brackets, I get unexpected character errors. For example, if I insert an empty computed section between methods a ...

What are some ways to retrieve a summary of an Angular FormArray containing controls?

In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed: FormGroup { controls { products (FormArray) { 0 : {summary.value: 5}... 1 : {summary.value: 8}.. there can be N of these co ...

Tips on transforming current JSON into an alternate JSON format

Using React with TypeScript, I have a JSON data set of employees categorized by their department. Here's a snippet of the JSON data: [ { "department": 1, "name": "Test", "age": 32, "contact": 242222120, "id": 1 }, { "department": 1, "name": "Te ...

Guide on how to prevent click events when a checkbox is not selected in Angular 2

A click event is being used on a ul element with a checkbox below it. When the checkbox is checked, the list should be enabled and the click event should work. If the checkbox is unchecked, the list should be disabled and the click event should not work. ...

Can you explain the functionality of the "lib" tsconfig option?

Hey, I'm currently working on a project and in the tsconfig.json file, there's this line: lib:["2016", "DOM"] Do you know what its purpose is? I did some research and came across this information: This setting specifies the library files to ...

What are the advantages of using interfaces in React?

Exploring Typescript's interface and its application in React has been an interesting journey for me. It seems that interfaces are used to define specific props that can be passed, acting as a form of protection against passing irrelevant props. My qu ...

Error: The method 'replace' is not a valid function for the specified

Something strange happened to my DatePicker today. All of a sudden, when I try to open it, the entire DatePicker appears white and I'm getting this error: > ERROR Error: Uncaught (in promise): TypeError: format.replace is not a function TypeError: ...

The Angular Date Pipe is displaying an incorrect date after processing the initial date value

Utilizing Angular's date pipe within my Angular 2 application has been beneficial for formatting dates in a user-friendly manner. I have successfully integrated API dates, edited them, and saved the changes back to the API with ease. However, an issue ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

JavaScript modules in Node.js do not support non-relative imports properly with Typescript

My goal is to develop a straightforward TypeScript script that utilizes ES modules, runs with node, and includes sourcemaps for debugging purposes. Here's the script that runs with node test.ts: import foo from './foo' //import bar from &a ...

Hiding components in Angular 4/5 through routing decisions

Just getting started with routing in Angular 4/5, I am currently following the tutorial provided on the official Angular website. I have an Angular application and I want to create two separate pages. Currently, the main page is located at localhost:8870/d ...

Mapping an array of JSON objects into a plain JSON object in TypeScript Angular 2: A Guide

Response Data: [ { "professionalId": { "cib_code": "30003", "thirdPartyId": "RS30004" }, "nationalIdentifier": "984538926", "nationalIdType": "SIREN" }, { "professionalId": { "cib_code": "30003", "thirdPar ...

"Exploring the power of fp-ts Option with Typescript and handling undefined

I am struggling to develop a straightforward helper function in fp-ts/Option and Typescript that can take any value and return it as an Option<T>. export const toOption = <T>(val: T): Option<T> => { return fromNullable(val); }; The ...

Angular component unable to retrieve array data from Angular service

I've developed an Angular service that serves as a middleman for fetching data from a database. Here's the code: export class WebService { constructor(private http: Http, private datePipe: DatePipe) { this.getStatsbyDate(this.datePipe.transf ...

Determining whether an option value has been selected in Angular

I am working on a template that includes mat-autocomplete for element searching, with individual option elements displayed. I am trying to implement logic where if an element is selected, the input should be disabled. How can I determine if a specific elem ...

Typescript - Iterating through CSV columns with precision

I am currently facing a challenge in TypeScript where I need to read a CSV file column by column. Here is an example of the CSV data: Prefix,Suffix Mr,Jr Mrs,Sr After researching on various Stack Overflow questions and reading through TypeScript document ...

Having trouble with DefaultAzureCredential in Azure

My current project involves utilizing Azure Storage, and to authenticate I am leveraging the DefaultAzureCredential. After logging in with the az login command, I encountered an error response when running my Azure function. { "message": "{& ...

What could be the reason for my function throwing a TypeError with the message "<function> is not a function"?

Every time I try to call a function that clearly appears to be defined as a function, I continuously receive the error message: TypeError: [function name] is not a function. To demonstrate the issue, here is a simple example: main.ts import someFunction ...