Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend.

The main objective is to have the app load a pre-existing list of notes from my MySQL database upon initialization.

However, upon making a GET request, I encountered an error message as shown below: https://i.sstatic.net/e6hke.png

Prior to this issue, I had dealt with CORS problems by adding http:// to my connection string. After resolving that, this new error appeared, and despite extensive research online, I have not been able to find a solution.

Below is my implementation in note.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Note } from '../note';

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

  private url: string = "http://localhost:44353/api/NotesLists";

  constructor(private http: HttpClient) { }

  getNotes(): Observable<Note[]> {
    return this.http.get<Note[]>(this.url);
  }
}

This code snippet shows how the app subscribes and retrieves responses in the home component:

import { Component, OnInit } from '@angular/core';
import { NoteService } from '../services/note.service';
import { Note } from '../note';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  public notes: Note[] = [];
  
  constructor(private noteService: NoteService) { }

  ngOnInit(): void {
    this.noteService.getNotes()
        .subscribe(data => this.notes = data);
  }

}

Furthermore, here is the [HttpGet] request implemented in the .Net Core backend:

    [HttpGet]
    public IActionResult Get()
    {
        try
        {
            var response = _datacontext.NotesList
                                        .Include(notesList => notesList.Note)
                                        .ToList();

            if (response.Count == 0)
            {
                return NotFound();
            }

            return Ok(response);
        }
        catch (Exception e)
        {

            return StatusCode(500, e.Message);
        }
    }

Lastly, for better contextual understanding, here is the DataContext utilized in the project:

using Microsoft.EntityFrameworkCore;
using noteAppAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace noteAppAPI.Helpers
{
public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> option) : base(option)
    {

    }

    public DbSet<NotesList> NotesList { get; set; }
    public DbSet<Note> Notes { get; set; }
    
}
}

Answer №1

Big thanks to @MarkHomer for his invaluable suggestion posted in the comments section. The resolution to this issue entailed:

Modifying the connection string within note.service.ts from

private url: string = "http://localhost:44353/api/NotesLists";

to

private url: string = "http://localhost:44353/api/NotesLists";

This adjustment necessitated enabling CORS within my API to facilitate the HTTPS request.

To activate CORS within Startup.cs, insert the following code snippet into the ConfigureServices method:

        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });
        services.AddDbContext<DataContext>(option => {
            option.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
        });

Furthermore, include the below code snippet within the Configure method of the same file:

        app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

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

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

Tips on updating arrow button icon when clicked using jquery

I am currently working on a project where I have a button icon that I want to change upon clicking it. I am using the following jQuery code: <script> $('div[id^="module-tab-"]').click(function(){ $(this).next('.hi').sl ...

What is the best way to reset state in a React component when a key is pressed down while typing in an input

I am struggling with handling input submission in a React component when the Enter key is pressed. My component is built using components from material-ui. In the onKeyDown event handler, I try to clear the state by setting the only field in the componen ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

What is the best way to create multiple AngularJS applications using NodeJS?

Upon completing the tutorial found at https://docs.angularjs.org/tutorial, I was inspired to create a new application on my local machine using AngularJS and NodeJS as the server. To start this new project, I made a separate folder at the same level as th ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

Utilize .GLB and Blender file formats within a Gridsome project developed with Vue.js

I am working on a project using Three.js in Gridsome, but I am facing difficulties importing .glb files (3D models) with GLTFLoader. While Gridsome recognizes img (png/jpg) or .js files stored in src/assets, it does not seem to support glb files. This is ...

The nodeJS function is still returning an error message, despite successfully saving the JSON data in MongoDB

Recently delving into nodeJS and mongoDB for the first time. Working on an application that utilizes nodeJS as the middleware, mongoDB as the database, and angularJS in the user interface. In nodeJS, I have set up controllers and models to handle business ...

Exploring the world of Bootstrap Twitter 3.0 alongside the wonders of Knockout

When utilizing Twitter Bootstrap, the validation classes like has-error or has-warning must be added to the wrapping form-group element to style both the input and its label. However, Knockout-Validation directly adds the class to the input element itself. ...

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...

The expiry date of the cookie remains unchanged

When attempting to create a cookie and specify an expiration date, I am encountering an issue where it remains as "Session". This problem is occurring in Google Chrome. I'm looking for insights on what might be causing this behavior. The code snippe ...

The reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-con ...

The pdf2json encountered an error when attempting to process a PDF file sent via an HTTP

I am encountering an issue while attempting to extract information from PDF files using a nodejs script. Upon running the program, I encounter the following error: Error: stream must have data at error (eval at <anonymous> (/Users/.../node_modules/ ...

Can one look through a div to the one beneath it by moving the cursor?

Hey there! I have a unique question for you. I've been trying to achieve a specific effect where two divs are stacked on top of each other, and the content of the lower div is only revealed in a certain area around the cursor. Is it possible to make o ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

Having trouble getting two different filters to work properly when filtering data in AngularJs

I have created a plunkr to demonstrate my current situation: The user is required to type a word into the textbox, and upon clicking the button, an angular service retrieves data from a DB based on the input text. The retrieved data is then displayed in a ...

Managing form submissions in React with inputs spread across multiple components

I've been working on a ReactJS project with a form that is divided into multiple components. The main component imports all the child components, each containing input boxes, along with a submit button: My issue lies in trying to get all the componen ...

What is the correct method to remove an item from local storage?

Using localStorage, I have stored multiple objects in an array. Is there a way to remove just one object from this array? If I use localstorage.removeItem(keysofthelocalstorage), I can delete the entire array, but I specifically want to remove only certai ...

Setting up AngularJS 1.5.x to function seamlessly with SystemJS and TypeScript

I'm looking to keep all my code in AngularJS 1.x while also preparing it for an easy upgrade to AngularJS 2 in the future. To align my code with Angular 2 standards, I am interested in using TypeScript and SystemJS in version 1.5.x initially. Is ther ...

Designing an advanced remote upload system using jQuery AJAX and PHP

Currently, I am in the process of developing an image hosting script and everything is going smoothly so far. To enable local uploading with drag & drop + AJAX, I have utilized various plugins which are working perfectly. Now, I am moving on to implementin ...