Encountering a 401 Unauthorized error due to CORS origin issue when making a post request with HttpClient in Angular

Encountering an error when trying to upload data to my backend Firebase database.

Here are the relevant code snippets:

storeUsers(users: any[]){
        return this.http.post('https://promise-90488.firebaseio.com/data.json', users);
    }

appcomponent.ts:

const result = Object.assign({}, this.userForm.value );
console.log(result);
this.userService.storeUsers(result)
      .subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );

The error messages are as follows:

POST 401 (Unauthorized) app.component.ts:37 HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "", ok: false, …} error: {error: "Permission denied"} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure response for : 401 Unauthorized" name: "HttpErrorResponse" ok: false status: 401 statusText: "Unauthorized" url: "" proto: HttpResponseBase

Answer №1

It appears that the authorization header is missing from your request

const httpOptions = {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token'
  })
};

return this.http.post('https://promise-90488.firebaseio.com/data.json', users, httpOptions);

For more information, please refer to the documentation here

To ensure that authorization headers are included in all requests, you can create an interceptor:

import { AuthService } from '../auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Retrieve the authorization token from the service.
    const authToken = this.auth.getAuthorizationToken();

    // Clone the request and update the headers with the authorization token.
    const authReq = req.clone({
      headers: req.headers.set('Authorization', authToken)
    });

    // Send the modified request with the header to the next handler.
    return next.handle(authReq);
  }
}

You can learn more about interceptors here

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

Tips for enhancing express.Request using tsserver and JSDoc

Recently, I have been utilizing tsserver with JSDoc in vim while working on a JavaScript project. Unfortunately, I've encountered an issue that needs resolving: /** @type {import('express').Handler} */ function requireUser(req, res, next) { ...

Accessing dynamically inserted child components in Angular 2.0

Currently, I am utilizing this sample to dynamically generate components within my application. export class App { @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef; private componentFactory: ComponentFactory<any> ...

Issue with Angular 2 AOT Compilation when trying to access formArray

This is the formGroup I created this.createOrderForm = this.fb.group({ items: this.fb.array([]) }); To add an item on button click addItem() { const control = <FormArray>this.createOrderForm.controls['items']; const a ...

Encountering an Issue while Attempting to Deploy Angular 6 on Her

I recently pushed my Angular 6 application to Heroku. Although the deployment was successful, the page is not loading properly. An error message on the page reads: An error occurred in the application and your page could not be served. If you are the ap ...

What are the best practices for effectively using RxJs subscriptions?

I'm looking for some advice on how to handle Angular and RxJs mechanics. I have server-side pagination set up on my backend and three components on the frontend: a data list, filters, and a pagination component. How can I subscribe to two streams (pag ...

Angular 2+ NgOnInit sets a value for an input array, however, it results in an error message stating that

One of the components in my application requires specific inputs, with the feedList being the most important one. Within the feedList, there are feed objects containing various data fields. However, some of these fields may be undefined depending on the fe ...

Implement static backgrounds on images within an Angular application

I am new to using Angular 7 and I have hit a roadblock. I need help understanding how to resize images so that either the height is 270 and the width is less than 470, or the width is 470 and the height is less than 270. Once resized, I want to place these ...

How to check all checkboxes in Angular using ngFor and ngIf?

Is there a way to select all checkboxes in an Angular form that uses ngFor and ngIf? I want to activate all checkboxes for the months when I click on "Select All". The list of months is stored in an array. Click here to see the HTML representation of the ...

Tips for automatically creating a categoryId using ObjectId for a category in Nest JS, Typescript, and Mongoose

book.entity.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import mongoose, { Document } from 'mongoose'; import { Category } from 'src/category/entities/category.entity'; export type BookDocument = Book & ...

Exploring the Fusion of GLTF Animations within Three.js in an Angular Environment

Currently, I am diving into an Angular project and have scoured the internet for solutions without any luck in determining a way forward. The challenge at hand involves 3 GLTF files portraying different facial expressions of a model (smiling, crying, laugh ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Angular2 date input field unable to restrict minimum and maximum dates

Having trouble with dynamic min and max attributes not being recognized in ionic2 when using the 'datetime-local' type. <ion-input value="" type="datetime-local" [formControl]="expdate" [attr.min]="mindate" [attr.max]="maxdate"></ion-in ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Using an array of strings as a key in React with TypeScript to access values from state

import React, { useState } from 'react'; interface PropsInterface { keys: string; // name,email,password } const Poster: React.FC<PropsInterface> = (props: PropsInterface) => { const [state, setState] = useState({ name: ' ...

How can you export the type of a private class in TypeScript without exporting the class itself?

I am facing a dilemma in my module where the public method of a public class is responsible for creating and returning a new instance of a private class. The stipulation is that only MyClass should have the capability to instantiate MyClassPrivateHelper. ...

Typescript Event Handling in React Select

I am facing an issue with my handleSelect function: const handlerSelectBank = (event: React.ChangeEvent<{ value: unknown }>) => { setState({ ...state, buttonDisabled: false, selectedBank: event }); }; Upon execution, I encountered ...

Exploring image cycling functionality in Angular by leveraging button clicks and services

I've been experimenting with cycling through images using button clicks in my code, but I haven't had much success so far. I tried a routing approach that didn't work out, resulting in me deleting the code. If anyone has any suggestions or c ...

The module 'atptest' could not be located or its corresponding type declarations are missing. Error code: ts(2307)

After creating an angular library using angular cli, I encountered an issue when trying to use it in any angular application after publishing it to npm. The published library installs successfully with the command: npm i atptest This is how I attempted t ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...