简体   繁体   English

Angular API 请求 .NET 5 API -.net::ERR_CONNECTION_REFUSE

[英]Angular API request to .NET 5 API - net::ERR_CONNECTION_REFUSE

Intro介绍

I am setting up an nginx server with angular universal as front-end and .NET 5 as a back-end API.我正在设置一个 nginx 服务器,angular universal 作为前端,.NET 5 作为后端 API。

Explanation解释

When trying to send a post request to the API i get an net::ERR_CONNECTION_REFUSED error.尝试向 API 发送发布请求时,出现net::ERR_CONNECTION_REFUSED错误。 You can try it out yourself here: https://modernamedia.no/#kontakt您可以在这里自己尝试: https://modernamedia.no/#kontakt

I have added console.logging for the error.我为错误添加了 console.logging。

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网络巡检

错误 1

错误 2

Could this possibly be a CORS issue?这可能是 CORS 问题吗?

Code代码

Angular - Contact service Angular - 联系客服

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 .NET - 启动

       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 .NET - 联系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}");
            }
        }
    }
}

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.大量 API 调用的问题在于,浏览器会告诉您这是某种 CORS 错误,但存在与 CORS 无关的潜在错误。

However here I think you need to set your client headers to match the backend CORS setup: -但是在这里我认为您需要设置客户端标头以匹配后端 CORS 设置:-

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.第二种方法是暂时从后端删除 CORS 以尝试隔离问题。

Also (unrelated but worth a look) your .NET controller is defined as: -另外(不相关但值得一看)您的 .NET controller 定义为:-

[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.它将找到默认的 POST 方法,因为它没有名称参数。 You could then define it more sepcifically like this: -然后你可以像这样更具体地定义它: -

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

then your url is: -那么您的 url 是:-

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

could this be a solution to your issue? 可以解决您的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM