How to get the return data from the api with Vue.js

Asked

Viewed 546 times

0

I am new to using Vue.js and have a problem getting back an api. My code is as follows::

div id="app">
    <ul>
        <li v-for="album in albuns">
            {{albuns.Id }} {{albuns.Nome}}
        </li>
    </ul>
</div>
<script src="https://unpkg.com/vue"></script>

<script>
const app = new Vue({
    el: '#app',
    data: {
        albuns: []
    },
    created() {
        fetch('http://localhost:59385/Album/listaralbuns')
            .then(Response => Response.json())
            .then(json => {
                this.albuns = json.albuns
            })
    }
})
</script>

Api

[HttpGet]
[Route("album/listaralbuns")]
public HttpResponseMessage ListarAlbuns(Album album)
{
    var albumService = new AlbumService();
    var listaAlbuns = albumService.obterAlbum();

    return Request.CreateResponse(HttpStatusCode.OK, 
        listaAlbuns, 
        Configuration.Formatters.JsonFormatter);
}

The api brings the correct data debugging by visual studio, but in return the following errors:

Access to fetch at 'http://localhost:59385/Album/listaralbuns' from origin 'http://localhost:59841' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource. If an Opaque Response serves your needs, set the request’s mode to 'no-Cors' to fetch the Resource with CORS disabled.

Test:1 Uncaught (in Promise) Typeerror: Failed to fetch

  • You are having Cors problem in your api, as you have not posted any information the api has not help. The Vue side looks okay but first you need to fix the api side

  • hello, I edited the question by also putting the list api, if you can take a look please

  • I think I was not very clear, you are having problem on the server side, when you make a request the browser before sending your request makes another request to the server which "operations" are free for it to do, if the "operation" is not released the browser will block your call, search google how to release CORS in your application

1 answer

1


Both Vue and API codes are correct, the problem that is when you connect the two, the name of this is CORS.

For security reasons, it is not possible to request a domain from one domain to another domain. To circumvent this you must inform that your API allows this external access, on this microsoft page they show in detail how to do this with C#.

Basically you just need to add a line before the declaration of your method to work.

...
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public HttpResponseMessage ListarAlbuns(Album album){
...
  • Hello sorry the delay in responding, it was the same Cors, thank you very much

Browser other questions tagged

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