How to send a post request using Axios and Asp.net Core Web API?

0

I am making a request with axios with the verb post , but I can not.

Note > With the verb get I can make the request.

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

Address Entity

   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 link : Response to   preflight request does not pass access control check: No   'Access-Control-Allow-Origin' header is present on the requested   resource. Origin ' link ' is therefore not allowed   access.

    
asked by anonymous 05.07.2018 / 13:32

1 answer

1

It looks like your JS is correct, but you need to enable CORS in your application .NET Core , in your Startup class, in the ConfigureServices method, 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 note that this policy will release all methods for all controllers , and this is a security breach, you should change this to make more specific when releasing to production.

Source: Enable requests between Origins (CORS) in the core of ASP.NET

    
05.07.2018 / 14:04