How to submit a post request using Xios and Asp.net Core Web API?

Asked

Viewed 1,468 times

1

I’m making a requisition with axios with the verb post, but I’m not getting it.

Note> With the verb get I can do the requisition.

Object

cliente: {
    nomeCompleto: '',
    cpf: '',
    email: '',
    endereco: {
        cep: '',
        logradouro: '',
        localidade: '',
        bairro: '',
        uf: ''
    }
}

Request

axios.post('http://localhost:62748/api/cliente', this.cliente)
  .then(response => {
      console.log(response)
  })
  .catch(function(error) {
      console.log(error)
  })

API

 [HttpPost]
 public void Post(
  [FromBody] Cliente cliente, [FromServices] ClienteRepository _repository) {
  _repository.Add(cliente);
 }

Client Entity

public int ClienteId {
 get;
 set;
}
public string Cpf {
 get;
 set;
}
public string NomeCompleto {
 get;
 set;
}
public string Email {
 get;
 set;
}
public Endereco Endereco {
 get;
 set;
}

Addressentity

   public int EnderecoId {
   get;
   set;
  }
  public string Cep {
   get;
   set;
  }
  public string Uf {
   get;
   set;
  }
  public string Localidade {
   get;
   set;
  }
  public string Bairro {
   get;
   set;
  }
  public string Logradouro {
   get;
   set;
  }

Allow-Control-Allow-Origin in Startup.cs and Configure

services.AddCors();

app.UseCors(builder => builder.WithOrigins("http://localhost:8080"));

Error

Failed to load http://localhost:62748/api/client: Response to preflight request doesn’t pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:8080' is therefore not allowed access.

  • Sopt colleague! Translate here!

1 answer

2


It seems your JS is correct, but you need to enable the CORS in its application .NET Core, in your class Startup, in the method ConfigureServices, add:

 services.AddCors(setup => {
  setup.AddPolicy("CorsPolicy", builder => {
   builder.AllowAnyHeader();
   builder.AllowAnyMethod();
   builder.WithOrigins("http://localhost:8080");
  });
 });

 services.Configure < MvcOptions > (options => {
  options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy"));
 });

Nota: It is important to stress that this policy will release all methods for all controllers, and this is a security breach, you should change this to make it more specific when releasing for production.

Source: Enable cross-source requests (CORS) in the ASP.NET core

  • Hahaha had not seen this in the documentation, but that was it :)

  • Can you explain to me why with the verb get I can make a request?

  • 1

    If I’m not mistaken when you add CORS with an origin, by default it releases GET, since it is a query verb. But for POST, PUT, DELETE it blocks, because in Restful pattern, are methods that change the state of something.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.