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

Angular API request to .NET 5 API - net::ERR_CONNECTION_REFUSE

简介

我正在设置一个 nginx 服务器,angular 通用 front-end 和 .NET 5 back-end API.

说明

当尝试向 API 发送 post 请求时,出现 net::ERR_CONNECTION_REFUSED 错误。 您可以在这里自己尝试一下:https://modernamedia.no/#kontakt

我已经为错误添加了 console.logging。

错误

错误:

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"

网络检查

这可能是 CORS 问题吗?

代码

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

       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 - 联系控制器


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}");
            }
        }
    }
}

很多 API 调用的问题是浏览器会告诉您这是某种 CORS 错误,但存在与 CORS 无关的潜在错误。

但是我认为您需要设置客户端 headers 以匹配后端 CORS 设置:-

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

尝试

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'
        })

第二种方法是暂时从后端删除 CORS 以尝试隔离问题。

另外(不相关但值得一看)您的 .NET 控制器定义为:-

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

我觉得这有点令人困惑,就我个人而言,我会这样做以便更清楚一点:-

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

然后调用

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

它将找到默认的 POST 方法,因为它没有名称参数。然后你可以像这样更具体地定义它:-

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

那么你的url是:-

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

this 可以解决您的问题吗?