Axios does not pass data to API Asp. Net Core

Asked

Viewed 198 times

-1

I searched every corner of the network for an answer and couldn’t find one and created an application with React that calls an Asp.Net core Webapi, using Axios. It turns out that the parameters do not arrive in the API method.

This is the call with Aces:

const config = {
  headers: {
    'Content-Type': 'application/json',
    'crossdomain': 'true'
  },
};
const params={
  Email: email,
  Password: password
}

await axios
.post(`${URL}?`,JSON.stringify(params), config)      
  .then((resp) => {
    data = resp.data;
  })
  .catch(function(err) {
    console.log(err);
    }        
  });

Esse é o método sendo chamado normalmente mas com os parametros null

This is the API Startup class

inserir a descrição da imagem aqui

If anyone can help, I’d be grateful.

Thank you

  • pass like this on this line: .post(${URL},params, config)

  • Virgilio Novic.. Follows null fields in api.

  • Only works if I pass the 'https://localhost:44318/api/Authen/login URL? Email=teste@email&Password=test'

  • Maybe something is configured wrong in the API.

  • await Axios . post(${URL}?email=${email}&password=${password}) . then((Resp) => { date = Resp.data; })

  • This way it works

  • I don’t know if it’s bad silver to wear like that

  • is bad practice and Asp controller has to be an object to work out now that I’ve noticed your code.

  • I switched to an Object and got the data, but how do I use it ? They’re coming in like this: Valuekind = Object : "{"Email":"testEmail","Password":"testNew"}".

Show 4 more comments

1 answer

0

Basically in order for your code to work, you must follow it as follows:

1- Create the template in a :

public class Login
{
    public string Email { get; set; }
    public string Password { get; set; }
}

2 - Create a method on controller:

[HttpPost("/login")]
public IActionResult Login (Login login)
{
    //login.Email
    //login.Password
    return Ok(login);
}

3 - Configure the Xios:

<script>
  function send() {
    const email = '[email protected]';
    const password = '123456';
    const data = { email, password };
    const url = 'http://localhost:49156/login';
    axios.post(url, data).then(function (response) {
      console.log(response);
    });
  }
</script>

3 - Perform the function send().

and with these 3 steps has the scenario of sending the request of the verb POST to the back-end .NET in class Login which follows the same name of the object passed in its front-end.

Observing: the addresses in the variable const url = 'http://localhost:49156/login' and en route [HttpPost("/login")] shall be amended in accordance with its.

  • Thank you so much for the support! Helped out 1000%. Success in your life!

  • vote on the issue as a solution to your problem

  • 1

    Thank you. Done!!

Browser other questions tagged

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