jeudi 30 juin 2016

$.post(url, data) and fetch(url, {method: 'POST', body: data}) not the same

I stuck on one small function. Trying to rewrite jQuery to JS ES6, and this function works correct:

$('#log-in-btn').on('click', function () {
                $('#login-error-message').empty().hide();
                var url = '/login/auth';
                var data = {
                    email: $('#email').val(),
                    password: $('#password').val()
                };

                var dest = $(this).data('dest');

                $.post(url, data, function (response) {
                    if (!response.result) {
                        $('#login-error-message').html(response.errorMessage).show();
                    } else {
                        if (dest !== '' && dest !== undefined) {
                            location.href = dest;
                        } else {
                            location.href = response.url;
                        }
                    }
                }, 'json');
            }); 

same function on JS return me error massage:

let loginBtn = document.getElementById('log-in-btn');

loginBtn.addEventListener('click', e => {
                    e.preventDefault();

                    let errorMessage = document.getElementById('login-error-message'),
                        dest = loginBtn.getAttribute('data-dest'),
                        data = {
                            email: document.getElementById('email').value,
                            password: document.getElementById('password').value
                        };

                    errorMessage.style.display = 'none';

                    fetch('/login/auth', {method: 'POST', body: data})
                        .then(res => res.json())
                        .then(res => {
                            if (!res.result) {
                                errorMessage.innerHTML = res.errorMessage;
                                errorMessage.style.display = 'block';
                            } else if (dest !== '' && dest !== undefined) {
                                location.href = dest;
                            } else {
                                location.href = res.url;
                            }
                        })
                        .catch(rej => document.getElementById('login-error-message').innerHTML = rej.message);
                });

What I'm doing wrong? just simple post request and in first case it works in second not?

Aucun commentaire:

Enregistrer un commentaire