Evitar error CORS

Ponemos lo siguiente en nuestra API:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDbContext<Contexto>(options =>
                   options.UseSqlServer(Configuration.GetConnectionString("MVCBasicContext")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseCors("MyPolicy");
            app.UseHttpsRedirection();
            app.UseMvc();
        }

Ejemplo acceso a web api

<script>

    fetch("https://localhost:44339/api/Alumnoes").then(resp => resp.json())
        .then(data => {
            for (alumno of data) {
                console.log(alumno.id + "-" + alumno.nombre + "-" + alumno.nota);
            }
        })

    let alumno = { nombre: "Firulai", nota: 8 };
    let params = {
        method: 'POST',
        body: JSON.stringify(alumno),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };
    fetch('https://localhost:44339/api/Alumnoes', params)
        .then(response => response.json())
        .then(json => console.log(json))

    alumno = { id: 9, nombre: "Firulai", nota: 6 };
    params = {
        method: 'PUT',
        body: JSON.stringify(alumno),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };
    fetch('https://localhost:44339/api/Alumnoes/9', params)
        .then(response => response.json())
        .then(json => console.log(json))
        .catch(error => console.log(error));

    params = {
        method: 'DELETE',
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };
    fetch('https://localhost:44339/api/Alumnoes/13', params)
        .then(response => response.json())
        .then(json => console.log(json))
        .catch(error => console.log(error));
</script>

Ejercicio mesa de poker

Vamos a crear una mesa de póker que tendrá:

2 usuarios personas
1 usuario robot
1 usuario que eres tú.

Para ello vamos a necesitar:

1.- Obtener dos usuarios aleatorios. Los podemos sacar de https://randomuser.me/api/?results=2
2.- Una cara de robot. La podemos sacar de: https://robohash.org/(nombre o valor). Ejemplo: https://robohash.org/7 o https://robohash.org/juanpablo
3.- Obtener una cara para nuestro avatar. Similar al anterior: https://api.adorable.io/avatars/200/juanpablo.png
4.- Obtener las cartas
Las podemos sacar de:
https://deckofcardsapi.com/
La url siguiente nos crea una baraja:
https://deckofcardsapi.com/api/deck/new/shuffle/
que tiene un deck-id

{
“success”: true,
“deck_id”: “3p40paa87x90”,
“shuffled”: true,
“remaining”: 52
}

Para obtener cartas tenemos la url:
https://deckofcardsapi.com/api/deck/<>/draw/?count=2
Nos devuelve las cartas:
{
“success”: true,
“cards”: [
{
“image”: “https://deckofcardsapi.com/static/img/KH.png”,
“value”: “KING”,
“suit”: “HEARTS”,
“code”: “KH”
},
{
“image”: “https://deckofcardsapi.com/static/img/8C.png”,
“value”: “8”,
“suit”: “CLUBS”,
“code”: “8C”
}
],
“deck_id”:”3p40paa87x90″,
“remaining”: 50
}

Tendremos que pedir cinco cartas por jugador.

En la página tendremos un botón que se encargará de vaciar la página, crear los usuarios y repartir las cartas.
Opcional: Averiguar la jugada de cada usuario y decir quién ha ganado.

Ejercicio usuarios

En la siguiente url:
https://randomuser.me/api/?results=3
Nos devuelve información aleatoria sobre usuarios.
Vamos a crear una web que al pulsar un botón nos pida por fetch a esa web 3 usuarios y nos muestre su nombre y su foto.

Ejercicio promesas

Vamos a crear una función cargar imagen a la que le pasemos una url e intente cargar la imagen, si existe la url y es una imagen que la ponga en un div. Si no hay imagen que ponga un mensaje de imagen no encontrada.
Con promesas.

Fetch ejemplo

<script>


    fetch('https://deckofcardsapi.com/api/deck/new/shuffle/')
        .then(
            function (response) {
                console.log(response);
                if (response.status !== 200) {
                    console.log('Looks like there was a problem. Status Code: ' +
                        response.status);
                    return;
                }

                // Examine the text in the response
                response.json().then(function (data) {
                    console.log(data);
                });
            }
        )
        .catch(function (err) {
            console.log('Fetch Error :-S', err);
        });

    fetch('https://deckofcardsapi.com/api/deck/new/shuffle/')
        .then(
            function (response) {
                return response.json()

                // Examine the text in the response

            }
        ).then(function (data) {
            console.log(data);
        })
        .catch(function (err) {
            console.log('Fetch Error :-S', err);
        });

    fetch('https://deckofcardsapi.com/api/deck/new/shuffle/')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(function (err) {
            console.log('Fetch Error :-S', err);
        });

    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
            title: 'foo',
            body: 'bar',
            userId: 1
        }),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    })
        .then(response => response.json())
        .then(json => console.log(json))

    let data = {
        title: 'foo',
        body: 'bar',
        userId: 1
    };

    let params = {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };

    fetch('https://jsonplaceholder.typicode.com/posts',params)
        .then(response => response.json())
        .then(json => console.log(json))
</script>