0

currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:

[HttpPost("login")]
    public async Task<IActionResult> Login([FromBody]User user)
    {
        var result = await _accountRepository.LoginAsync(user.username, user.password);

        if (string.IsNullOrEmpty(result))
        {
            return Unauthorized(result);
        }

        Debug.WriteLine(result.ToString()); // this works and I can see the token
        return Ok(result);

    }

When it comes here:

  methods: {
login() {
  fetch("http://localhost:60427/api/account/login", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json', 
'Accept': 'application/json',
    },
    body: JSON.stringify({
      username: this.username,
      password: this.password,
    })
  }).then(response => {  
      console.log(response.data); // this is always undefined 
      
    })  
    .catch(e => {  
      console.log(e);  
    });  
},

}

Please help I can't see any errors here. I'm confused.

6
  • 1
    Try: console.log(response.text()); Commented Jan 4, 2022 at 21:55
  • Hey thanks for that, it helped a bit but now I'm getting pending promise and I can see my token. How can I access that? Commented Jan 4, 2022 at 22:20
  • 1
    Without knowing anything about your API it's not clear what your response object structure would be. I would look at console.log(response) then, after that it's a matter of using.dot.notation.to.get.your.data. Commented Jan 4, 2022 at 22:20
  • Thank you so much. Commented Jan 4, 2022 at 22:23
  • This isn't how fetch api is used. You'd have response.data in Axios, but fetch isn't axios. Commented Jan 4, 2022 at 22:38

1 Answer 1

2

You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.

E.g. for JSON:

fetch("http://localhost:60427/api/account/login", {
  method: "POST",
  headers: {
    'Content-Type': 'application/json', 
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    username: this.username,
    password: this.password,
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.error(e));
Sign up to request clarification or add additional context in comments.

1 Comment

This method worked but not exactly because the second then method after fetch comes after json() not the first then method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.