Consume via JQuery-Ajax, an API at localhost: 28033, from a page at localhost: 7545

1

I'm trying to do something, but it's not working. I have two .Net Core 2.0 projects, an API, and an MVC.

I want to run ajax calls from the MVC project, to the Project Controllers API.

I open two visual studios, and I run two projects:

Run the API project: link

And I run the AspNetCore MVC Interface project link (login screen, which makes the jquery call)

When I enter my email and password, and I click the Enter button, from localhost: 7545, my API, which is on the link , respond as follows:

            UsuarioAutenticado = new UsuarioAutenticado()
            {
                Autenticacao = Autenticacao,
                Token = Token,
                Usuario = Usuario
            };

            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            Response.Headers.Add("Access-Control-Allow-Credentials", "false");
            Response.Headers.Add("Access-Control-Allow-Method", "POST");
            Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
            Response.Headers.Add("Content-Type", "application/json");

            return Result(UsuarioAutenticado);

When I run through Postman, it returns the following:

Headers:

access-control-allow-credentials → false

access-control-allow-headers → Content-Type

access-control-allow-method → POST

access-control-allow-origin → *

cache-control → no-cache

content-type → application / json

date → Sat, 07 Jul 2018 01:18:58 GMT

expires → -1

pragma → no-cache

server> Kestrel

transfer-encoding → chunked

Body:

{     "message": null,     "isSuccess": true,     "date": {         "user": {             "person physics": null,             "Physician ID": 1,             "username": "admin",             "password": null,             "id": 1,             "dataCriacao": "2018-06-24T20: 11: 40.99",             "datechange": null         },         "authentication": {             "idToken": 6,             "sessionId": "cf3b8d67-4b22-4fc0-b72e-882f77fec078",             "isAuthenticated": true,             "id": 17,             "dataCriacao": "2018-07-06T22: 18: 58.6775345-03: 00",             "datechange": null         },         "token": {             "user": null,             "idUsuario": 1,             "dataExpiration": "2018-07-06T22: 30: 09.617",             "TokenCode": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MzA5MjcwMDksImlzcyI6IlNJTlVDQUJSQVNJTC5DT00uQlIiLCJhdWQiOiJTSU5VQ0FCUkFTSUwuQ09NLkJSIn0.OJnTTGqiPv3mOealCzjd0M2uG_tKVhFY2_Vn77YnINU"             "isValid": true,             "id": 6,             "dataCriacao": "2018-07-06T22: 00: 09.677",             "datechange": null         }     } }

That is, it works ok.

But when I put my information through the form, I call JQuery:

    var host = 'http://localhost:28033/api/';

    $("#btnEntrar").on('click', function () {

    try {
        var login = $("#emailLogin").val();
        var senha = $("#passwordLogin").val();
        var lnkEsqueciSenha = $("#lnkEsqueciSenha").val();

        if (login.length == 0) {
            throw "Digite o seu e-mail";
        }

        if (senha.length == 0) {
            throw "Digite a sua senha";
        }

        $.ajax({
            url: host + 'token/autenticar',
            type: 'POST',
            dataType: 'JSON',
            data: { nomeUsuario: login, senha: senha },
            xhrFields: {
                withCredentials: false
            },
            success: function (data) {
                var result = data;

                $("#modalErro").html(result);
                $("#modalErro").show();

                if (!isSuccess) {
                    throw result.message
                }

                $("#btnEntrar").attr('disabled', 'disabled');
                $("#btnEntrar").text('Carregando...');

                window.location = '/';
            },
            error: function (xhr, status, error) {
                $("#modalErro").show();
                $("#modalErro span").text(xhr.responseText);

                $("#btnEntrar").text('Entrar');
                $("#btnEntrar").removeAttr('disabled');
            },
            beforeSend: function () {
                $("#btnEntrar").text('Aguarde...');
                $("#btnEntrar").attr('disabled', 'disabled');
            },
            complete: function () {
            }
        });
    }
    catch (e) {
        $("#modalErro span").html(e);
        $("#modalErro").show();
    }
});

It gives Chrome an error:

Failed to load link : In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' link ' is therefore not allowed access.

When I see the header in chrome, the following comes:

Cache-Control: no-cache

Content-Type: application / json; charset = utf-8

Date: Sat, 07 Jul 2018 01:33:47 GMT

Expires: -1

Pragma: no-cache

Server: Kestrel

Set-Cookie: ASPNetCoreSession = CfDJ8KnuUrc2899Bt9ImKJiMxmqcTuiTpwF 2B9cGui15c5yZfjUTRBvsAuwoyRK71gZ5rbpS6Ounjce2fcKUKBR1z1DWDiz9P%%% 2Bykm 2BI39rkU% 2BWD5ntbTc8A8e 2B9wy6MV4kKbGDSApTNeLzzCUk19k8SDzDTWplB7ZCRLkJlZf4s0KqV6U%; path = /; samesite = lax; httponly

Transfer-Encoding: chunked

That is, they did not return:

access-control-allow-credentials → false

access-control-allow-headers → Content-Type

access-control-allow-method → POST

access-control-allow-origin → *

Could you guide me, please?

    
asked by anonymous 07.07.2018 / 03:46

1 answer

2

Eduardo,

You need to enable .NET CORS CORS.

Inside the .NET Core Project Startup within the ConfigureServices method adds:

services.AddCors();

and within the Configure method add:

app.UseCors(x =>
        {
            x.AllowAnyHeader();
            x.AllowAnyMethod();
            x.WithOrigins(
                "http://localhost:7545",
            );
        });

If it does not work replace the link with an asterisk (*) for testing purposes, because the address is the URL of your calling application the API. and you can add multiple URL's.

NOTE: You must enter your production URL as well.

    
09.07.2018 / 19:44