Gyldstrand Gyldstrand - 5 months ago 70
Ajax Question

AJAX 404 with Node and Koa

Browser JS

'use strict';

window.onload = () => {


let form = document.getElementById('sign_up_form'),
username = form.elements[0],
password = form.elements[1],
confirm = form.elements[2],
email = form.elements[3],
errors = document.getElementById('sign_up_errors');

username.addEventListener('change', (e) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', '/validate_username');
xhr.send();

xhr.onreadystatechange = () => {
console.log(xhr.readyState);
if (xhr.readyState === 4) {
console.log(xhr.status);
if (xhr.status === 200) {
console.log('AJAX SUCCESS');
};
};
};
});

confirm.addEventListener('change', (e) => {
if (password.value != confirm.value) {
errors.children[1].innerHTML = 'Passwords do not match.';
} else {
errors.children[1].innerHTML = '';
};
});

form.addEventListener('submit', (e) => {
e.preventDefault();

let form_data = {
username: username.value,
password: password.value,
confirm: confirm.value,
email: email.value,
};

let xhr = new XMLHttpRequest();
xhr.open('POST', '/validate_signup');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(form_data));
});
}


Server

'use strict';

let app = require('koa')(),
serve = require('koa-static'),
router = require('koa-router')(),
parse = require('koa-bodyparser'),
mongo = require('koa-mongo'),
fs = require('co-fs');

app.use(serve(__dirname + '/public'));

app.use(mongo({
uri: ******,
max: 100,
min: 1,
timeout: 30000,
log: false
}));


app.use(parse());
app.use(router.routes());

router.post('/validate_username', function *(next) {
console.log('username:');
console.log(this.request.body);
});

router.post('/validate_signup', function *(next) {
console.log('signup:');
console.log(this.request.body);
this.mongo.collection('users').findOne({'username': this.request.body.username}, (err, doc) => {
console.log(doc);
});
});

app.listen(5000);


The AJAX 'POST' request gives the form_data to the server and I can check the database but consoles 404 error. The AJAX 'GET' request just throws a 404 error after achieving readyState 4. I think I am using the routes incorrectly or am missing something in my AJAX requests but I am new to Koa.js and pretty much green all around so any help will be appreciated.

Answer

JS:

'use strict';

window.onload = () => {


    let form = document.getElementById('sign_up_form'),
        username = form.elements[0],
        password = form.elements[1],
        confirm = form.elements[2],
        email = form.elements[3],
        errors = document.getElementById('sign_up_errors');

    username.addEventListener('input', (e) => {
        let data = {username: username.value};

        let xhr = new XMLHttpRequest();
            xhr.open('POST', '/sign_up/username');
            xhr.setRequestHeader('Content-type', 'application/json');
            xhr.send(JSON.stringify(data));
            xhr.onreadystatechange = () => {
                console.log(xhr.readyState);
                if (xhr.readyState === 4 && xhr.status === 200) {
                    if (JSON.parse(xhr.responseText).username) {
                        console.log('unavailable');
                    } else {
                        console.log('available');
                    };                    
                };
            };
    });
};

SERVER:

'use strict';

let router = require('koa-router')({
    prefix: '/sign_up'
});

router.post('/username', function *(next) {
    console.log('Checking username...');

    yield new Promise((resolve, reject) => {
        this.mongo.collection('users').findOne({'username': this.request.body.username}, (err, doc) => {
            if (doc) {resolve(doc)} 
            else {reject()};
        });
    }).then((doc) => {
        if (doc) {
            console.log('Promise: ' + doc);
            this.body = {username: false};
        };
    }).catch(() => {
        console.log('Promise rejected.');
        this.body = {username: true};
    });
});


module.exports = router;