skip to Main Content

Intro

I am setting up an nginx server with angular universal as front-end and .NET 5 as a back-end API.

Explanation

When trying to send a post request to the API i get an net::ERR_CONNECTION_REFUSED error.
You can try it out yourself here: https://modernamedia.no/#kontakt

I have added console.logging for the error.

Error

Error:

POST http://localhost:5000/API/Contact/Contact net::ERR_CONNECTION_REFUSED
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: ro {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:5000/API/Contact/Contact: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:5000/API/Contact/Contact"

Network inspection

Error 1

Error 2

Could this possibly be a CORS issue?

Code

Angular – Contact service

export class ContactService {
  constructor(private http: HttpClient, private toast: ToastService) {}
  private SendCTAMessageURL = environment.url + '/API/Contact/Contact';
  headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  public errorMessage;
  public SendContactRequestResult = new BehaviorSubject<boolean>(false);
  SendContactRequest(model: any) {
    var request = this.http.post<any>(this.SendCTAMessageURL, model);
    var response;
    request.subscribe({
      next: (data) => {
        this.toast.Toast(
          'Melding sendt!',
          'Vi kontakter deg snarest!',
          'default',
          5000
        );
        this.SendContactRequestResult.next(true);
        response = true;
      },
      error: (error) => {
        this.errorMessage = error.message;
        console.error('There was an error!', error);
        this.toast.Toast(
          'Det oppstod en feil!',
          'Kontakt oss på tlf: 902 65 326!',
          'error',
          10000
        );
        this.SendContactRequestResult.next(false);
        response = false;
      },
    });
    return response;
  }

.NET – Startup

       public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ModernaMediaDotNet v1"));
            }
            app.ConfigureExceptionHandler(logger);
            app.UseRouting();
            app.UseCors(x => x
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .SetIsOriginAllowed(origin => true) // allow any origin
                    .AllowCredentials()); // allow credentials

            //app.UseHttpsRedirection();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

.NET – Contact Controller


namespace ModernaMediaDotNet.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ContactController : ControllerBase
    {

        private ITwillioService twillioService;
        private readonly ILoggerManager logger;

        public ContactController(ITwillioService twillioService, ILoggerManager logger)
        {
            this.twillioService = twillioService;
            this.logger = logger;
        }

        [HttpPost]
        public IActionResult Contact(ContactModel model)
        {
            string body = $"Melding fra MODERNA MEDIA: n" +
                $"navn: {model.name} n" +
                $"epost: {model.email} n" +
                $"telefon: {model.phone} n" +
                $"bedrift: {model.business} n" +
                $"tittel: {model.title} n" +
                $"innhold: {model.body}";
            logger.LogInfo("Initializing message");
            logger.LogInfo(body);
            try
            {
            var result = twillioService.SendMessage(body);
                return Ok(result);
            }
            catch (System.Exception e)
            {
                logger.LogError($"Something went wrong: {e}");
                return StatusCode(500, $"Internal server error: {e}");
            }
        }
    }
}

2

Answers


  1. The issue with a lot of API calls is that a browser will tell you it is some kind of CORS error but there is an underlying error that has NOTHING to do with CORS.

    However here I think you need to set your client headers to match the backend CORS setup: –

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

    try

    headers = headers: new HttpHeaders({
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': 'localhost:5000',
              'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
              'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token, content-type'
            })
    

    A second approach is to remove CORS temporarily from the backend to try and isolate the issue.

    Also (unrelated but worth a look) your .NET controller is defined as: –

    [Route("api/[controller]/[action]")]
    

    I find this a bit confusing, personally I would do it like this to give a little more clarity: –

    namespace ModernaMediaDotNet.Controllers
    {
        [Route("api/[controller]")] // No action here
        [ApiController]
        public class ContactController : ControllerBase
        {
          ...
    

    Then call

    private SendCTAMessageURL = environment.url + '/API/Contact';
    

    It will find the default POST method as it has no name parameter. You could then define it more sepcifically like this: –

            [HttpPost("Submit")]
            public IActionResult Contact(ContactModel model)
            {
              ...
    

    then your url is: –

    private SendCTAMessageURL = environment.url + '/API/Contact/Submit';
    
    Login or Signup to reply.
  2. could this be a solution to your issue?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search