Read response in json via a fetch with service-worker

Asked

Viewed 45 times

1

I am implementing a web notification system, using service-worker and other components, in Asp.net MVC.

1° I already have my worker registered and started on the system.
2° I can display notifications now.

-- Foul --
Correctly read the answer a function returns.

In my controller, I have this function that returns the message to be displayed in the notification:

[HttpGet]
[AllowAnonymous]
public JsonResult GetNotificacao()
{
    //Recupera cookie
    var cookie = Request.Cookies.Get("UsuarioId");
    if (cookie == null) return Json(null, JsonRequestBehavior.AllowGet);

    //Convert para int e pesquisa o registro
    var usuario = int.Parse(cookie.Value);
    var push = db.Notificacoes.FirstOrDefault(x => x.Colaborador_id == usuario && x.Recebido == 0);

    //Se for nulo, retorna null
    if (push == null) return Json(null, JsonRequestBehavior.AllowGet);

    //Cria o payload da mensagem
    var payload = new CasNotificacao
    {
        Colaborador_id = push.Colaborador_id,
        Titulo = push.Titulo,
        Mensagem = push.Mensagem
    };

    //Atualiza no banco que foi exibida
    db.Database.ExecuteSqlCommand($"update CasNotificacao set Recebido = 1 where IdNotificacao = {push.IdNotificacao}");

    //Retorna o conteúdo no format json
    return Json(payload, JsonRequestBehavior.AllowGet);
}

When the return exists, the payload is this:

{"IdNotificacao":0,"Colaborador_id":393,"Titulo":"Notificação Teste","Mensagem":"Apenas um corpo de teste","Recebido":0,"DataEnviado":"\/Date(-62135589600000)\/"}

The important thing about payload is, title and message.

In my service-worker I have the following code that checks a new push:

self.addEventListener("push", function () {
    fetch("http://localhost:21181/Servidor/GetNotificacao", {
        method: "get",
        mode: "no-cors",
        headers: {
            "Accept": "application/json",
            'Content-Type': 'application/json'
        }
    })
        .then(function (data) {
            console.log(data);
            var options = {
                body: "tste thiago",
                icon: "../images/logo.png"
            }
            self.registration.showNotification("Site", options);
        })
        .catch(function (error) {
            console.log('Request failed', error);
        });
});

The problem is... The message fetch picks up, I’m unable to interpret... the reason: it’s not entering the function, because the update in the database is not running...

Fetch exit: Saída do fetch

No answers

Browser other questions tagged

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