Transforming Post Requests into Options Requests

I am facing an issue with my Angular 6 API. After creating interceptors, my POST requests are turning into OPTIONS requests.

What could be causing this problem?

Here is the code for one of the Services:

import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { AppConfig } from '../app.config';
import { Perfil } from '../Entities/Perfil';

@Injectable({
  providedIn: 'root'
})
export class UsuariosService {

  constructor(private http: HttpClient, private config: AppConfig) { }

  private per = new Perfil(1);

  getPerfiles() {
    return this.http.post(this.config.apiUrl + 'perfiles/Buscar/', this.per);
  }


}

Take a look at this image for further insight into the issue:

https://i.sstatic.net/x9p9r.png

Thank you!

Answer №1

The issue at hand is related to CORS, as mentioned by lomboboo. The OPTIONS request is a specific inquiry directed towards the server to determine permissions for accessing content.

To resolve this issue, you must configure CORS headers on your server (backend) and permit requests like POST, as well as any other necessary operations.

Answer №2

//**Make sure to include the necessary header in your POST API request**

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

fetchProfiles() {
    return this.http.post(this.config.apiUrl + 'profiles/Search/', this.per, httpOptions).subscribe(result => {
        console.log(result);
      }, error => console.log('An error occurred:'));
};
}

Answer №3

Yes! I finally figured out that they were the cors issue, and I tried implementing a solution in the backend, but it didn't work out as expected. The approach I took to solve this was:

(using .Net Framework 4 )

public static void Register(HttpConfiguration config)
        {

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
         }

Special thanks to lomboboo and Mike, your assistance was greatly appreciated!

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

Exploring an array within an object using Typescript and React

As a newcomer to TypeScript and React, I have a project where I need to extract data from a JSON file (back-end) and display it on cards (front-end). I am trying to pass props using cards?.items.map, but I'm uncertain about the correct way to access ...

The issue of the Angular 4 double click event not functioning properly on mobile devices

I have implemented a double click functionality in my code, which is working perfectly in desktop view. However, I am facing an issue when switching to mobile or tablet view as the double tap feature does not work. Below is a snippet of my code: HTML: & ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

:id Path replaces existing routes

My route configuration looks like this: const routes: Routes = [ { path: '', component: UserComponent, children: [ { path: '', component: LoginComponent }, { path: 'signup', component: SignupComponent } ]}, ...

Is there a way to specifically choose the initial element using Angular? "Backend powered by Django"

Hi there! I've set up Django on the back-end to send data to Angular, and I'm trying to display only the first comment from a list in my HTML page. However, when using limitTo, I encountered this error: Failed to compile. src/app/app.component. ...

retrieving and presenting information stored in a Firebase repository

I am currently working on retrieving data from a firebase database and storing it in an array called courses that I have declared within my class. Here's the code I have so far: import { AngularFireDatabase, AngularFireList } from 'angularfire2 ...

An issue has arisen where Selenium Auth0 is unable to establish a connection with the server

I am using a protractor selenium test for an angular2 application that I execute with the command protractor conf.js --params.login.username=John --params.login.password=Doe. The purpose of the test is to attempt to log in to the backend and intentionally ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

Encountering issues during the installation of node modules within an Angular application

I encountered an issue while setting up my angular app. Upon trying to install the node modules using the command npm i --save, I received the following error message. Error: npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network This is a pr ...

Is it feasible to pre-render an Angular2 view invisibly when hovering?

Can a view be preloaded and prerendered invisibly upon hover? I have an application that displays a list of items. Each item is its own component, and when you click on any of these items, it is replaced by a detailed view (another component) of the same ...

Progress Bar Modules

I am currently working on creating a customizable animated progress bar that can be utilized as follows: <bar [type]="'health'" [percentage]="'80'"></bar> It is functional up to the point where I need to adjust different p ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...

What is the best way to handle updating an npm package that is not the desired or correct version?

I've been experimenting with querying data on Firebase using querying lists. My attempt to implement functionality similar to the documentation resulted in this code snippet: getMatchesFiltered(matchId: string, filter: string, sortDirection: string, ...

Angular Universal - Transfer state does not populate correctly when the URL contains unsafe characters, leading to duplicate XHR calls

Working with Angular(12) and Angular Universal has presented me with a challenge regarding the transfer state between the server and client side. On the client side, I am using the TransferHttpCacheModule, while on the server side module, I have implemente ...

Bringing TypeScript modules from a local module into a React application

As I work on organizing my projects and keeping logic separate in components that will eventually be published, I have a specific structure set up for now: I have a library of Typescript scripts within a project named project-a A separate React app create ...

What's the best way to include various type dependencies in a TypeScript project?

Is there a more efficient way to add types for all dependencies in my project without having to do it manually for each one? Perhaps there is a tool or binary I can use to install all types at once based on the dependencies listed in package.json file. I ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

Differences between Strings and Constants in React While Using Redux for Action Types

In the Redux guide, it is suggested to define strings constants for Redux action types: const FOO = 'FOO'; const BAR = 'BAR'; dispatch({ type: FOO }); It's worth noting that most concerns raised are relevant to untyped JavaScrip ...