The TypeScript alternative to Axios request with native fetch functionality

I have a function that sends a JWT validation request:

const sendValidateJWTRequestFetch = (url: string, token: string) =>
  fetch(url, {
    method: 'GET',
    mode: 'cors',
    headers: {
      Authorization: token,
      'Access-Control-Allow-Origin': '*'}
  })
  .then(response =>
    response.ok ? response : Promise.reject<Response>(response)
  )
  .then(response => response.json())
  .then(data => data.Token)

While it works fine in my development environment, I'm facing some CORS issues in production. To resolve this, I want to switch to using axios for the get request. Here's what I have tried:

const sendValidateJWTRequest = (url: string, token: string) =>
  axios.get(url, {
    headers: {Authorization: token, 'Access-Control-Allow-Origin': '*'},
    crossDomain: true
  })
  .then(resp => resp.data ? resp : Promise.reject<Response>(resp))
  .then(response => response);

However, I am encountering an error while working with TypeScript. The error can be viewed here. How can I resolve this issue?

In order to enable crossDomain: true, I had to make the following addition to the code:

declare module 'axios' {
  export interface AxiosRequestConfig {
    crossDomain: boolean;
  }
}

Answer №1

There appears to be an issue related to the Response type - as it is being retrieved from the fetch API, it does not align with what Axios uses. These two libraries do not have compatible typings. It is recommended to utilize AxiosResponse instead.

Another discrepancy to note is how errors are managed differently between Axios and FetchAPI. In Fetch, there is a .ok property and resolved promise, whereas in Axios, the promise would be rejected if the server returns a status > 400. This means you do not need to manually reject the response, but can use .catch to handle any exceptions accordingly.

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

The React Hooks Dilemma: Why Axios State Won't Update

Encountering an issue where the setAuth state is not updating within the axios call. Attempted to update the state after the API call only if the HTTP status code is 200, but the state remains unchanged. export default function SignIn() { const clas ...

Mongoose encountered an error when attempting to cast the value "ObjectID" to an ObjectId at the specified path "red.s1"

My Mongoose schema is structured as follows: const gameSchema = new Schema({ matchNumber: { type: Number, required: [true, 'A match must have a number!'], unique: true }, red: { s1: { type: ...

There is no index signature that includes a parameter of type 'string' in the specified type

I have a background in mobile app development and am looking to learn more about TypeScript. How can I declare a map object with the form [string:any]? The error is occurring at line: map[key] = value; Element implicitly has an 'any' type becaus ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Node-fetch enables dynamic requests

Seeking to retrieve real-time data from a fast-updating API has posed a challenge for me. The issue lies in my code constantly returning the same value. I've experimented with two approaches: var fetch = require("node-fetch"); for(let i=0; i<5; i+ ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Can the Date class be expanded by overloading the constructor method?

In my dataset, there are dates in different formats that Typescript doesn't recognize. To address this issue, I developed a "safeDateParse" function to handle extended conversions and modified the Date.parse() method accordingly. /** Custom overload ...

Initial ReactJS fetch result is not defined

Currently, I am implementing a basic fetch operation from my backend express server. Upon the first click of the "Submit" button, I receive an "undefined" response. However, on the second click of the "Submit" button, I successfully retrieve the expected ...

Cypress automation script fails to trigger Knockout computed subscription

Within my setup, I have implemented two textboxes and a span to display the result. Date: <input data-bind="value: dateValue"/> Number: <input data-bind="value: dateValue"/> Result : <span data-bind="text: calculatedValue">Result Should ...

Using Axios with Mongoose to Update Documents in Not Working State

I'm currently working on implementing an edit feature for updating posts. My goal is to initially update a specific post by its ID and then make it more dynamic. Although I am able to successfully send a PUT request using axios, I'm not getting ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

The properties in Typescript, specifically 'value', are not compatible with each other

I've encountered an error while working on a TypeScript project with React Context. The error message states: Argument of type 'Context<{}>' is not assignable to parameter of type 'Context<IsProductContext>'. The type ...

Challenges with deploying Angular applications and dealing with undefined properties within Angular code

Currently, I have successfully added new products to the database with all the desired properties. However, I am facing errors that are preventing me from deploying the application for production. Fixing these errors causes further issues where I cannot ad ...

What is the best way to incorporate an additional feature into vue.js?

Is it possible to add multiple get posts in Vue.js? I have successfully implemented a single post function, but I'm unsure how to incorporate multiple post functions. Here is my current code snippet: <script> new Vue({ el: '#app' ...

The function does not yield any result

import { Injectable } from '@angular/core'; export class Test { public id: number; public name: string; public fid: number }; export const TESTS2: Test[] = [ {id: 1, name: 'Lion', fid: 1}, {id: 2, name: 'Tiger', fid: 1 ...

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

Leveraging the power of NestJS in conjunction with Apollo Server version 2

I recently delved into learning nestjs and decided to give this graphql example a try. The issue I encountered is that the example was originally designed for apollo-server version 1, and I'm having difficulty adapting it to work with apollo-server v ...

Set up linter rules that utilize `useEffect` in place of `React.useEffect` (utilizing named export rather than full export)

It's important in our codebase to always use: import { useEffect } from 'react'; instead of: import React from 'react'; // use in code as `React.useEffect` Can we enforce this rule with longer eslint rules? If so, how can we impl ...

Mismatched data types caused by immutability

I'm having trouble with my object that has a middleware property and the types aren't working as expected. The error message is stating that the two middlewares are incompatible because one of them is set to readonly. Does anyone know how I can r ...

Although VSCode is functioning properly, there seems to be a discrepancy between the VSCode and the TS compiler, resulting in an

While developing my project in VSCode, I encountered an issue with accessing req.user.name from the Request object for my Node.js Express application. VSCode was indicating that 'name' does not exist in the 'user' object. To address thi ...