skip to Main Content

I rarely dive into web development and was using the following link to build a small project: https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-angular?view=vs-2022

Using this project I’ve gone to rename the controller and now when loading the page the request returns a 404. If I name it back the page loads as expected (in the three components below by renaming Products to WeatherForecast). The 3 places I re-named are below. This is still using dummy data as I learn angular.

What am I missing by doing a simple rename here?

product.component.ts:

 export class ProductComponent implements OnInit {
 public forecasts?: Products[];

 constructor(http: HttpClient) {
 http.get<Products[]>('/products').subscribe(result => {
  this.forecasts = result;
}, error => console.error(error));
}

proxy.conf.js:

const PROXY_CONFIG = [
  {
    context: [
      "/products",
    ],
    target: "https://localhost:7050",
    secure: false
  }
]

module.exports = PROXY_CONFIG;

Products controller:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [ApiController]
     [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<ProductsController> _logger;

        public ProductsController(ILogger<ProductsController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetProducts")]
        public IEnumerable<Products> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new Products
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

404:enter image description here

2

Answers


  1. According to your HttpErrorResponse, you are not sending request to .NET API, but to localhost:4200 which I believe is your Angular application.

    Try sending request like this:

    http.get<Products[]>('https://localhost:7050/products').subscribe...
    

    If that works, your proxy configuration is messing with the request. Be sure to get the port right and to start Angular application after .NET application has started. You can check your ports in launchSettings.json, be careful because http and https use different ports. Use http if your certificates are not configured.

    Don’t forget to include proxy.conf.json in angular.json under "serve" like this:

    "architect": {
      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "browserTarget": "your-application-name:build",
          "proxyConfig": "src/proxy.conf.json"
        },
    
    Login or Signup to reply.
  2. To extend @Ocram’s answer – which is absolutely correct and relevant -, I also found that if you have a context: [] list in your PROXY_CONFIG definition in the proxy.conf.js file (the list of paths/controllers you want to redirect to the backend port), then you need to ensure that this list contains all the controller names you need.

    It is because when you rename a controller, you also need to inform the client proxy config about the change.

    const PROXY_CONFIG = [
        {
            ///-----------------
            context: [  
                "/weatherforecast",
                "/test",
                "/mynewapi",
            ],
            ///-----------------
            changeOrigin: true,
            target: target,
            secure: false,
            headers: {
                Connection: 'Keep-Alive'
            }
        }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search