Having trouble sending an HTTP request to my .Net Core 2.1 web project

In my current project, I am working with Angular 6 and .Net Core 2.1. The Angular 6 code is in one project, while the .Net Core 2.1 controller methods for login authentication are in another project. I have noticed that both projects are using different localhost port numbers. While I can successfully receive results when making API calls from Postman, I am facing an issue when trying to post data from the Angular service to the controller method.

Specifically, I need to post login credentials to the ValuesController method. However, every time I try to do so, I encounter an HttpErrorResponse.

Scenario 1:

When both the Angular 6 code and the controller (SampledataController) method are in the same project, I can successfully post the request and get a response.

Scenario 2:

The issue arises when the Angular 6 code is in one project and the .Net Core 2.1 controller methods for login authentication are in another project. This communication flow is from (WebProject) LoginService ----> (Api) ValuesController.

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

LoginService.ts

AuthenticateUser(txtUsername: string, txtPassword: string) {

    this.userRoles.UserName = txtUsername;
    this.userRoles.Password = txtPassword;
    let parameters = new HttpParams().set('txtUsername', txtUsername)
                                     .set('txtPassword', txtPassword);
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    const httpOptions = { headers: headers };
    return this._httpClient.post(this.base_url + "SampleData/AuthenticateUser/" + txtUsername + "/" + txtPassword , httpOptions);
}

ValuesController.cs

[Route("[controller]")]
    public class ValuesController : ControllerBase
    {

        [Route("[action]/{UserName}/{Password}")]
        public ActionResult<IEnumerable<string>> AuthenticateUser(string UserName, string Password)
        {
            return new string[] { UserName, Password };
        }

Below is my solution structure

Solution
    --> Angular project
         Components
               --login component
         Services
               --Login service
         Controller
               --SampleDataController

    --> WebApi Project
         --Controller
              -- ValuesController

Please assist me in resolving this issue as I am new to this. Thank you in advance!

Answer №1

Based on the information provided, it seems like enabling CORS may be the solution to your issue. Postman does not send a preflight request, unlike browsers. Additionally, improper handling of Server responses could be causing the strange 404 error. This might be due to your API attempting to redirect to a non-existent login page.

To enable CORS for all domains, you can add app.UseCors(); in the Configure method of your Startup file.

For more detailed instructions on enabling CORS, please refer to the documentation here:

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2

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 retrieving the text from a POST request in C#

I have a basic Angular form that allows users to upload a file along with a description. constructor(private http: HttpClient) { } upload(files) { if (files.length === 0) return; const formData: FormData = new FormData(); var filedesc ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

"Exploring data trends with an ng2-charts line graph displaying x and y axis values

I am attempting to showcase a function using ng2-charts, with a specific set of x and y values. However, the display is currently not showing my values correctly. https://i.sstatic.net/1iULy.png Here is an example dataset: chartDataSet: ChartDataSets[] = ...

Steps to establish a maximum font size for my buttons

I've been working on creating buttons to decrease and increase the font size of my text. The functionality is there, but I want to establish a limit on how small or large the font can go. Here's what my current code looks like: <md-button ng ...

What causes the "This page isn't responding" error to pop up in Edge and Chrome browsers while attempting to perform consecutive tasks in a web application built with Angular 8?

Trouble with Page Loading Whenever this error occurs, I find myself unable to perform any activities on that page. The only solution is to close the tab and open a new one. My current code allows me to navigate through an array list (Next and Previous) us ...

What makes React Native unique when it comes to handling multiple data inputs?

Apologies for my limited English skills. I am trying to structure multiple data entries by adding separate JSON lines for each input, but currently it updates the previous data instead of creating a new one. Below is the sample code I am working with. var ...

The Angular Material tab component fails to display on the webpage

I am encountering an issue with the Angular Material Tabs Module where only text is being displayed instead of the actual tabs. I am using Angular 6 along with Angular Material version 6.4.7. After following the setup procedure outlined on (npm installat ...

Are AngularJS Material Components compatible with Angular2?

Recently, I inherited a web app project from a former colleague who has since moved on from our company. The web app was originally built using Angular2 as its framework, but it seems that the previous developer attempted to incorporate AngularJS Material ...

Implementing Angular 2 reactive forms checkbox validation in an Ionic application

I have implemented Angular Forms to create a basic form with fields for email, password, and a checkbox for Terms&Conditions in my Ionic application. Here is the HTML code: <form [formGroup]="registerForm" (ngSubmit)="register()" class="center"> ...

TypeDoc fails to generate documentation for an Express JS API and displays no information

As I strive to document my Express JS API using TypeDoc, I am encountering an issue where the generated documentation is quite empty. https://i.sstatic.net/LRhOE.png This outlines my API file structure: https://i.sstatic.net/6zuXQ.png Below is a snippet ...

Utilizing RouterLink along with a button and conditional rendering in Angular

One issue I am facing is using *ngIf to navigate to a different page based on a variable. Despite having valid links, when I click on the button nothing happens. Here is the code snippet: <button mat-button > <span class=&quo ...

Conceal the menu in Angular Material when the mouse leaves the button

When the mouse hovers over a button, a menu is displayed on the website's toolbar. The menu is set to close when the mouse leaves a surrounding span element. Now, there is an attempt to also close the menu when the mouse leaves the triggering button i ...

Angular4 Datatable Integration with Firebase

Issue encountered with Datatable, Angular 4, and Firebase I suspect the problem lies in the usage of | async as it is not generating a valid JSON object. HTML Markup <tr *ngFor="let item of items | async; let i = index"> <th scope="row">{ ...

Angular: how to manually trigger change detection without using Angular's dependency injection system

Is there a way to globally initiate angular change detection without having to inject something like ApplicationRef? I am looking to utilize the functionality as a standard JavaScript function rather than a service method, in order to avoid the need for ...

Creating a numeric sequence based on the date of a corresponding transaction - a step-by-step guide

INTRO I built an e-commerce app with TypeScript and Sequelize ORM. In the app, I have a table that generates sequential invoice numbers based on the current day. CREATE TABLE `dm_generate_trx` ( `id` int NOT NULL AUTO_INCREMENT, `date` date NOT NULL, ...

Navigating the enum data model alongside other data model types in Typescript: Tips and Tricks

In my different data models, I have utilized enum types. Is it possible to compare the __typename in this scenario? enum ActivtiyCardType { Dance, ReferralTransaction, } type ActivityCardData = { __typename:ActivtiyCardType, i ...

Incorporate ES6 Promise directly into Typescript for enhanced Protractor/WebDriverJS ControlFlow capabilities

Currently, I am incorporating external code in my Protractor tests that yield ES6 Promises. I had the intention of chaining these promises using a ControlFlow, but I encountered a type error during Typescript compilation. Within the test: import {browse ...

Tips for Retrieving Information from Firebase in an Angular Application

I am facing an issue with my code where the ngFor directive is not working as expected when I use read_CheckOuts to return data from the database. Below are snippets of my code: crud.service.ts import { AngularFireDatabase} from '@angular/fire/datab ...

What steps should I take to troubleshoot an error with accessing 'request.body' within an async function that is returning a 'ReadableStream' object instead of the data I was expecting?

While developing my CRUD functionality in Next.js with TypeScript and Prisma, I encountered an issue with the PUT method. The GET method handler works fine, but for some reason, the PUT method is causing errors that I'm struggling to resolve. When in ...

Why is there always a reference to the previous data every time I create a new component?

I am currently working on a component that retrieves data from a service through an event message: this.objectDetailsSubscription = this.eventService.subscribe( EventsChannels.OBJECT_DETAILS, semantic => { this.layer = this.layerSem ...