How can I send a POST request in TypeScript?

I am new to Angular 9 and facing an issue with headers in my post request. The error message says:

Unnecessarily quoted property 'Authorization' found
. What does this mean? What is it asking for? How can I resolve it?

serviceName.service.ts:

export class DadataSuggestService {
   url = 'https://cleaner.dadata.ru/api/v1/clean/name';
   token = 'f6bf5c998d0e4fcd58cea3b241763e01fe918127';
   secret = 'c6461196cb75f4f880b07f9bf5fb58b7a715b245';
    query = 'Срегей владимерович иванов';
  constructor(private http: HttpClient) {
  }
  options: {} = {
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Token ' + this.token,
      'X-Secret': this.secret
    },
    body: JSON.stringify([query])
  };

  takeSuggestion(URL: string, options: object): any {
    return this.http.post(URL, options)
      .pipe(
        tap(
          data => console.log(data),
          error => console.log(error)
        )
      );
  }
}

Answer №1

When utilizing the post function directly, there is no need to explicitly specify the method. To send the headers, consider implementing the following:

sendRequestToAPI(URL: string): any {
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'Token ' + this.token,
    'X-Secret-Key': this.secretKey
  });
  const options = { headers };
  const requestBody = JSON.stringify([query]);

  return this.http.post(URL, requestBody, options).pipe(
    tap(
      response => console.log(response),
      err => console.log(err)
    )
  );
}

Answer №2

To enhance security, consider implementing an HTTP interceptor that automatically adds the token to your requests. If that is not feasible, you can try the following alternative approach:

var headers = {
  headers: new HttpHeaders()
    .set('Authorization', `Bearer ${AuthService.getToken()}`)
}

this.http.post(url, data, headers)

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

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

Angular release 6: A guide on truncating text by words rather than characters

I'm currently enhancing a truncate pipe in Angular that is supposed to cut off text after 35 words, but instead it's trimming down to 35 characters... Here is the HTML code: <p *ngIf="item.description.length > 0"><span class="body-1 ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

Encountering issues with `npm run build:prod` on Ubuntu 16.04, whereas it runs smoothly on

I've encountered errors when attempting to run "npm run build:prod" on Ubuntu 16.04, even though I don't face the same issues on Windows 10. Both npm and node are up-to-date. It's unclear whether the problem lies with npm or angular. After ...

Customized interfaces utilizing generic components

Here is my simplified question. interface Identity{ name: string; } Next, we have a generic interface. interface State<T extends Identity>{ [T.name] : StateContainer<T> } Unfortunately, this approach fails and the following error is ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Extract the content of a nested JSON object in ReactJS using map function

I am encountering an issue while attempting to map nested JSON data, specifically the error 'Element implicitly has an 'any' type'. The problem arises within the search component at: Object.keys(skills[keyName]).map() Below is the cod ...

Retrieve contextual information within standard providers

I'm currently using nestjs to create a straightforward HTTP rest API, utilizing typeorm. I have set up 2 Postgres databases and would like the ability to access both, although not necessarily simultaneously. Essentially, I am looking to designate whi ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

Display the list of cities associated with the country chosen in the form

I am currently working with the repository found at https://github.com/country-regions/country-region-data/blob/master/data.js to create a mapping of countries and their related cities. I'm seeking guidance on how to achieve this task effectively. My ...

Creating modern web applications using Angular and .Net Core with the power of Bootstrap 4

Has anyone experimented with developing an application using the following commands? dotnet new --install Microsoft.AspNetCore.SpaTemplates::* dotnet new angular You can find an example of this at this link. By default, the command creates an Angular + ...

Unveiling the Ultimate Method to Package Angular 2 Application using SystemJS and SystemJS-Builder

I'm currently in the process of developing an application and I am faced with a challenge of optimizing the performance of Angular 2 by improving the loading speed of all the scripts. However, I have encountered an error that is hindering my progress: ...

Combining JavaScript files can cause conflicts with duplicate identifiers when using Typescript namespaces

As a newcomer to Typescript, I am grappling with the concept of namespaces and how to reference Interfaces that are defined in separate files. Coming from a .NET C# background, I am used to creating each class and interface in their own file. INationalRai ...

WebStorm is not implementing the exclude option as specified in the tsconfig.json file

Is there a way to exclude a directory from TypeScript compilation in WebStorm? Despite specifying the exclusion in the tsconfig.json file, it seems that WebStorm doesn't respect the setting and compiles everything in the root directory. However, runn ...

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 ...

Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total pric ...

Unexpected outcomes when using three.js getWorldPosition method

Please check out the gist I put together over at https://gist.github.com/sparkbuzz/f1f8d0d8bbc7757b679f In this gist, you'll find a TypeScript class named OrbitControls. I've been delving into 3D and three.js to explore creating orbit-style con ...

What is the process for implementing a new control value accessor?

I have a directive that already implements the ControlValueAccessor interface (directive's selector is input[type=date]) and now I need another directive that also implements ControlValueAccessor with the selector input[type=date][datepicker] - let&ap ...

Is it appropriate to incorporate existing cshtml markup from MVC into Angular 6?

I am currently working on a project that involves migrating an MVC application to Angular6. The designs for this project are already created in cshtml files, which are essentially views. My question is, would it be acceptable to use these existing designs ...