The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that the fetch options include the Authorization header. However, when using POST or PATCH methods, the Authorization header disappears immediately after being added to the object. Below is my request method:

const send = async (apiOptions: ApiParams): Promise<FetchReturn> => {
    const accessToken = GetAccessToken()
    const options: ApiOptions = {
        method: apiOptions.method,
        headers: {
            Authorization: `Bearer ${accessToken}`
        }
    }

    console.log(options)

    if (apiOptions.data) {
        options.headers = {
            'Content-Type': 'application/json'
        }
        options.body = JSON.stringify(apiOptions.data)
    }

    const result = await fetch(`${getUrl()}/${apiOptions.path}`, options).then(res => res).catch(err => err)
    if (!result.ok) {
        if (IsExpired()) {
            const refreshResult = await fetch(`${getUrl()}/api/user/refresh`, {method: 'POST', headers:{
                'Content-Type': 'application/json'
            }, body: JSON.stringify(GetRefreshRequest())}).then(res => res).catch(err => err)
            if (refreshResult.ok) {
                Login(JSON.parse(await refreshResult.text()))

                return await send(apiOptions)
            } else if (refreshResult.status === 401) {
                Logout()
                window.location.reload()
                return { code: 0, text: ""}
            }
        }
    }
    const text = await result.text()
    return { code: result.status, text: text }

}

Answer №1

It seems that you may have an 'apiParams' property assigned to the POST method, with a later if-condition that entirely replaces the request headers object. Let's update it as follows:

    options.headers['Content-Type'] = 'application/json';

This will ensure that the authorization remains in the headers.

Answer №2

Make sure to always check the value of your apiOptions.data before proceeding.

In my experience, this value tends to be null when making a POST/Patch request.

To troubleshoot, insert a console.log("...") within an if statement and see if that helps resolve any errors.

If you're still facing issues, feel free to leave a reply below this post.

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

Can someone help me locate the file using the inspect element feature?

Today, I encountered a small issue on my website that I wanted to fix. Although I was able to make the necessary changes using Inspect Element, I couldn't locate the file where it needed to be changed. The website in question is gesher-jds.org/giving. ...

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

Extract the value from an array of objects

https://i.sstatic.net/fTShc.png Having some difficulty accessing the elements of an array. In order to assign a project name to a local variable projectName, I am seeking assistance with extracting the project name from the given JSON structure. Any hel ...

Upon clicking the submit button, retrieve all the table rows that have been selected

After populating a table with data from a CSV file, users have the ability to select specific rows. When they click submit, all selected row data is sent to a webservice. Although I have successfully implemented AngularJS(v1.6) to populate the data and re ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Unexpected Issue with ASP.net Dynamic Controls Generation

In my reporting module developed in C# asp.net, I have implemented dynamic controls to represent the various parameters of selected reports. The process of building and displaying these dynamic controls works smoothly thanks to XML stored in SQL Server 20 ...

Tips on employing the sendkeys function in selenium webdriverjs through promise chaining

Here is the coding snippet: driver.get(url).then(function(){ txtFnn = driver.findElement(webdriver.By.xpath(xpath)); return txtFnn; }).then(function(){ txtFnn.sendkeys("12345678"); }) Issue: An error occurred: Typ ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

Encountered an issue with instafeed.js due to CORS policy restrictions

Trying to implement an API that provides JSON data for use in a function. Required Imports: Importing Jquery, instafeed.min.js, and the API (instant-tokens.com). <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js& ...

Like button for Facebook located at the bottom of a static webpage

I am facing an issue with my web application where it does not scroll properly, especially when there is a Facebook button at the bottom. The behavior in Chrome and Firefox is inconsistent and causing some trouble. In Chrome, the div repositions correctly ...

Mongodb failing to recognize the concat function

I have a field within my collection that looks like this: uniqueId: 123 inTarefa: true exclude: "ab,cd," orderId: 987 I am attempting to update all of the values using a "FindOneAndUpdate" query like so: collection.findOneAndUpdate({ 'uniqu ...

What is the process for sending an HTTP post request with a React/Typescript frontend and a C#/.Net backend?

In the frontend code, there is a user login form that accepts the strings email and password. Using MobX State Management in the userstore, there is an action triggered when the user clicks the login button to submit the strings via HTTP post. @action logi ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Mixing box-shadow and blur filters can result in unusual artifacts appearing in Webkit browsers

Recently, I encountered an intriguing and frustrating bug in WebKit browsers. Consider a scenario where there is a parent DIV (let's say .wrapper) and a child DIV (.main). You apply a box-shadow on the .main DIV and a blur filter on the .wrapper DIV. ...

Is there a way to display the HTML input date by simply clicking on text or an image?

I need to display a date picker when I click on specific text or an image. I am working with reactjs and utilizing the HTML input type="date", rather than the React-datepicker library. Here is the code snippet: import { useRef } from "r ...

What could be causing the predefined string error in useState when using TypeScript?

Is it possible to set a predefined string (enum) in React's useState hook? I attempted the following: const [color, setColor] = React.useState<"red | blue">("blue"); however, an error was thrown: Argument of type '& ...

I'm struggling to find the perfect configuration for Vite, JSconfig, and Aliases in Visual Studio Code to optimize Intellisense and Autocomplete features

After exclusively using PHPStorm/Webstorm for years, I recently made the switch back to Visual Studio Code. The main reason behind this decision was the lightweight nature of VSCode and its widespread availability as a free tool, unlike paid services. I s ...

A guide on how to associate data in ng-repeat with varying indices

Here is the data from my JSON file: var jsondata = [{"credit":"a","debit":[{"credit":"a","amount":1},{"credit":"a","amount":2}]}, {"credit":"b","debit":[{"credit":"b","amount":3},{"credit":"b","amount":4},{"credit":"b","amount":5}]}, {"credit":"c","debi ...

Trigger a notification based on the selected choice

Here is some sample HTML code: <div id="hiddenDiv" style="display: none;"> <h1 id="welcomehowareyou">How are you feeling today?</h1> <select name="mood" id="mood"> <option value="" disabled selected>How are you feeling?</o ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...