Consume via Jquery-Ajax, an API on localhost:28033, from a page on localhost:7545

Asked

Viewed 262 times

0

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

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

I open two visual Studios, and have run two projects:

Run the API project: http://localhost:28033/api/token/authenticate

And run the Aspnetcore MVC Interface project http://localhost:7545/login (Login screen, which makes the call jquery)

When I enter my email and password, and click on the Login button, from localhost:7545, my API, which is on http://localhost:28033, answers the following:

            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 for Postman, the next comes back:

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": { "personal Phiisica": null, "idPessoaFisica": 1, "noun": "admin", "password": null, "id": 1, "dataCreation": "2018-06-24T20:11:40.99", "date Change": null }, "Appliance": { "idToken": 6, "sessionId": "cf3b8d67-4b22-4fc0-b72e-882f77fec078", "isAuthenticated": true, "id": 17, "date": "2018-07-06T22:18:58.6775345-03:00", "date Change": null }, "token": { "user": null, "idUsuario": 1, "dataExport": "2018-07-06T22:30:09.617", "tokenCode": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MzA5MjcwMDksImlzcyI6IlNJJTlVDQUJSQVNTC5DT00uQlILCJhdWQiOiJTSU5VQ0FCUkTSUwuQ09NNLkJSIn0.Ojnttgqipv3moealczjd0m2ug_tkvhfy2_vnyninu", "isValid": true, "id": 6, "date": "2018-07-06T22:00:09.677", "date Change": null } } }

I mean, it works okay.

But when I put my information in the form, and call in 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 an error in Chrome:

Failed to load http://localhost:28033/api/token/authenticate: No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:7545' 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

Exhale: -1

Pragma: no-cache

Server: Kestrel

Set-Cookie: Aspnetcoresession=Cfdj8knuurc2899bt9imkjimxmqctuitpwf%2B9cGui15c5yZfjUTRBvsAuwoyRK71gZ5rbpS6Ounjce2fcKUKBR1z1DWDiz9P%2Bykm%2BI39rkU%2BWD5ntbTc8A8e%2B9wy6MV4kKbGDSApTNeLzzCUk19k8SDzDTWplBZCRLLkJlZ4s0KqV6U; path=/; samesite=Lax; tphtonly

Transfer-Encoding: chunked

I mean, the:

access-control-allow-credentials false

access-control-allow-headers Content-Type

access-control-allow-method POST

access-control-allow-origin*

Could you direct me, please?

  • In ajax enter: crossDomain: true

1 answer

1


Eduardo,

You need to enable . NET Core CORS.

Within the Project Startup . NET Core within the Configuraeservices method adds:

services.AddCors();

and inside the Configure method adds:

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

If it doesn’t work, change the http://localhost:7545 by an asterisk (*), testing afim, because the address is the URL of your application that calls the API. and you can add multiple URL’s.

NOTE: You must inform your production URL as well.

Browser other questions tagged

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