Search code examples
node.jsservicerequesthttp-status-code-404feathersjs

Feathers service does not found during fetch request


I make post request, by the fetch, to add new user to database. The response that i get is 'POST http://localhost:3000/register 404 (Not Found)'. The problem is in the fact that, even after returning 404 to frontend, backend still continue the operation and adds user to DB.

Fetch request on frontend:


let res = await fetch('http://localhost:3000/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                login: login,
                password: password,
                role: role
            })
        });

Backend feathers service:


const registrator = {
    async create(data, params) {
        let Model = app.get('Model');
        Model.create({ login: data.login, password: data.password }, (err) =>{
            if (err) {
                return err;
            }
            else {
                Right.create({ login: data.login, rights: data.role },(err)=>{
                    if (err) {
                        Model.findOneAndRemove({ login: data.login });
                        return err;
                    }
                    else {
                        return data;
                    }
                });
            }
        });
    }
}

String that defines path to this service:


app.use('/register', registrator);


Solution

  • To fix this, you should return something from main body of service. If 'return' is inside promise, node defines it as service that do not return anything, that's why we get this error. My service after fixing:

    const registrator = {
        async create(data, params) {
            let Model = app.get('Model');
            return await Model.create({ login: data.login, password: data.password })
                .then(() => {
                    Right.create({ login: data.login, rights: data.role })
                })
                .then(() => {
                    return data;
                }).catch(err => {
                    Model.findOneAndRemove({ login: data.login });
                    Sentry.captureException(err);
                });
        }
    }
    

    This way 'data' would return only if operation was successful, so we can check result of operation on frontend part.