Encountering a 405 HTTP error in Angular8 app when refreshing the page

Currently, I am working on a project using Angular8 and .NET Core 3.0 in Visual Studio. Everything is running smoothly except for one issue that arises when I press F5 on a page with a form. The error message that pops up reads:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed) [http://localhost:51871/notifications]

The submit function in the component class looks like this:

  onSubmit() {

    if (this.registerForm.invalid) {
      return;
    }

    let post: NotificationsInterface = {
      email: this.registerForm.value.email,
      subject: this.registerForm.value.subject,
      text: this.registerForm.value.text,
    };

    this.http.post("Notifications", post).subscribe(result => {
      console.error("ok");

    }, error => console.error("error"));

  }

This is the C# notification class:

public class Notifications
{
    public string email { get; set; }
    public string subject { get; set; }
    public string text { get; set; }
}

And here is the controller in C#:

using Microsoft.AspNetCore.Mvc;
using HomeHelper.Models;

namespace HomeHelper.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class NotificationsController : Controller
    {
        [HttpPost]
        public IActionResult Post([FromBody]Notifications notification)
        {

            return Ok();

        }
   }
}

I have noticed that by commenting out the controller part in C#, the error disappears but data cannot be received. What would be the best approach to prevent such errors in the future? This particular error only occurs in the URL "http://localhost:51871/notifications".

UPDATE: I have added the full code of the controller along with the specified error-inducing URL.

Answer №1

To troubleshoot this issue, consider setting up a GET route in your controller with the same endpoint.

If you are experiencing problems when refreshing your Angular application and landing on the route localhost:51871/notifications, it may be due to the server not having a GET method configured. This results in an error as the browser sends a GET request upon refresh.

Consider switching to a hash location strategy or modifying the angular route. Ensure that all backend API URLs function properly by including the api path in the URL, such as

localhost:51871/api/notifications
, to track which API is being called.

Answer №2

To improve your routing, consider implementing the hash location strategy.

RouterModule.forRoot(routes, {useHash: true})

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

Issue encountered: The differ cannot recognize the provided object '[object Object]', which is of type 'object'. NgFor is limited to binding Iterables only

I have been following a tutorial on Ionic created by Paul Halliday, focusing on a shopping list project that utilizes Firebase and Angular. However, I am encountering an error every time I try to run the application: Error: Uncaught (in promise): Error: ...

Refreshing a component without having to reload the entire page in Angular4: A step-by-step guide

I have an application built with Angular 4 that consists of two components - one for adding items and another for viewing them. I am facing an issue where the view page does not update with the new item added. Although I can see the updated data source, th ...

Best practice for incorporating types into a Redux-toolkit reducer

As someone who is relatively new to TypeScript, I have a specific goal in mind. I am looking to create an interface where: interface ActionType { fieldName: {any one key from the interface FormStateType listed below such as 'name', 'age&ap ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Deleting an element from a two-field object in TypeScript 2

I am working with a 2-field object structure that looks like this { id: number, name: string } My goal is to remove the name field from this object. How can I achieve this in TypeScript? I have attempted using methods like filter and delete, but all I r ...

Why do we often encounter a "SyntaxError: Unexpected token ;" error when a seemingly normal semicolon is present in distribution files?

Currently, I am in the process of developing a newsletter subscription API using node.js and typescript. This project involves my first experience with typeorm and PostgreSQL. Following several tutorials, I configured typeorm and created the entity types a ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

ASP.NET MVC - Naming conventions for displaying the entire model

I am aware of the DisplayName and Display attributes for model properties, like in this example: public class MyModel { [Display(Name = "Licence")] public string Licence { get; set; } } However, I am curious if there is a way to have a Display a ...

Angular: Navigating to a distinct page based on an API response

In order to determine which page to go to, based on the response from an API endpoint, I need to implement a logic. The current API response includes an integer (id) and a string (name). Example Response: int: id name: string After making the API call, I ...

retrieve information from Angular service

Is there a way for parent components to communicate with child components by injecting providers directly into the TypeScript file of each child component? I am trying to retrieve data using get and set methods, but I am unsure how to proceed. Any suggesti ...

What is the best way to dynamically set an ID in Angular using the pound symbol (#)?

I am currently developing a dynamic Angular 6 application that utilizes dynamic components. My approach involves using @ViewChild('<id>', { read: ViewContainerRef }) <id>; to reference the divs where I intend to populate with dynamic ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Angular Material select all checkboxes provide a convenient way to select multiple

Need help with implementing a select all checkbox on Angular Material. The goal is to have the master checkbox show Indeterminate when a specific item is clicked, and then turn to checked once all checkboxes are selected. Currently experiencing some unexpe ...

I am experiencing issues with my Angular2 project where not all of my component variables are being passed to the

My problem involves sending three variables to my HTML template, but it only recognizes one of them. The HTML template I am using looks like this: <div class="page-data"> <form method="post" action="api/roles/edit/{{role?.ID}}" name="{{role? ...

Expanding external type declarations within Typescript

I am currently working with Typescript and the ant design library. My goal is to extend an existing interface by adding a single property. To start, I imported the original interface so you can see the folder structure: import { CollapseProps } from &apo ...

Continuously apply the template in a recursive manner in Angular 2 without reintroducing any duplicated components

Recently, I delved into the world of angular 2 and found it to be quite fascinating. However, I'm currently facing a roadblock and could really use some assistance. The scenario is as follows: I am working on creating a select box with checkboxes in ...

Event typeORM on afterUpdate in NestJS

After every update of my data in the log table, I want to insert an entry into another table. To achieve this, I have created an EntitySubscriberInterface. The event is triggering correctly, but the entity array does not include the updated id. async afte ...