Two custom methods/endpoints using loopBack, one works, the other gives a 401











up vote
0
down vote

favorite












I created two custom endpoints with Loopback.



Account.deleteAllHearingTests = function (req, callback) {
console.log('here comes the req to delete all hearing tests', req);
Account.findById(req.accessToken.userId)
.then(account => {
if (!account) {
throw new Error('cannot find user');
}
return app.models.HearingTest.updateAll({ accountId: account.id }, { isDeleted: new Date() });
})
.then(() => {
callback(null);
})
.catch(error => {
callback(error);
})
}
Account.remoteMethod(
'deleteAllHearingTests', {
http: {
path: '/clearHearingTests',
verb: 'post'
},
accepts: [
{ arg: 'req', type: 'object', http: { source: 'req' } }
],
returns: {}
}
);


the second one looks like this.



Account.deleteSingleHearingTest = function (req, callback) {
// console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
Account.findById(req.accessToken.userId)
.then(account => {
if (!account) {
throw new Error('Cannot find user');
}
console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });

})
.then(() => {
callback(null);
})
.catch(error => {
callback(error);
});
}

Account.remoteMethod(
'deleteSingleHearingTest', {
http: {
path: '/deleteSingleHearingTest',
verb: 'post'
},
accepts: [
{ arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
],
description: 'this is the end point for a single delete',
returns: {}
}
);

};


The first custom method returns a 401 status response when I make the initial fetch. The second returns a 200.



Inside my actions file the first method is called with something that looks like this:



export function deleteAllHearingTests() {
return (dispatch, getState) => {
let state = getState();
if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
console.debug('deleteAllHearingTests', state.user);
// TODO: ERROR
return;
}
fetch(SERVERCONFIG.BASEURL + '/api/Accounts/clearHearingTests?access_token=' + state.user.accessToken.id, {
method: 'POST',
headers: SERVERCONFIG.HEADERS
})
.then(response => {
console.log('here is your response', response);
if (response.status !== 200) {
throw new Error('Something is wrong');
}
return response.json()
})


the second method is called with



export const deleteSingleHearingTest = (hearingTestNumber) => {
return (dispatch, getState) => {
let state = getState();
if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
console.debug('writeTestResult', state.user);
// TODO: ERROR
return;
}
console.log('single delete ', SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id)
fetch(SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id, {
method: 'POST',
headers: SERVERCONFIG.HEADERS,
body: JSON.stringify({ "hearingTestId": hearingTestNumber })


})
.then(response => {
console.log('getting response from initial fetch inside deleteSingleReqport', response);


They are nearly identical, however, one works..the other fails. What are some possible causes for the 401?










share|improve this question


























    up vote
    0
    down vote

    favorite












    I created two custom endpoints with Loopback.



    Account.deleteAllHearingTests = function (req, callback) {
    console.log('here comes the req to delete all hearing tests', req);
    Account.findById(req.accessToken.userId)
    .then(account => {
    if (!account) {
    throw new Error('cannot find user');
    }
    return app.models.HearingTest.updateAll({ accountId: account.id }, { isDeleted: new Date() });
    })
    .then(() => {
    callback(null);
    })
    .catch(error => {
    callback(error);
    })
    }
    Account.remoteMethod(
    'deleteAllHearingTests', {
    http: {
    path: '/clearHearingTests',
    verb: 'post'
    },
    accepts: [
    { arg: 'req', type: 'object', http: { source: 'req' } }
    ],
    returns: {}
    }
    );


    the second one looks like this.



    Account.deleteSingleHearingTest = function (req, callback) {
    // console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
    Account.findById(req.accessToken.userId)
    .then(account => {
    if (!account) {
    throw new Error('Cannot find user');
    }
    console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
    return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });

    })
    .then(() => {
    callback(null);
    })
    .catch(error => {
    callback(error);
    });
    }

    Account.remoteMethod(
    'deleteSingleHearingTest', {
    http: {
    path: '/deleteSingleHearingTest',
    verb: 'post'
    },
    accepts: [
    { arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
    ],
    description: 'this is the end point for a single delete',
    returns: {}
    }
    );

    };


    The first custom method returns a 401 status response when I make the initial fetch. The second returns a 200.



    Inside my actions file the first method is called with something that looks like this:



    export function deleteAllHearingTests() {
    return (dispatch, getState) => {
    let state = getState();
    if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
    console.debug('deleteAllHearingTests', state.user);
    // TODO: ERROR
    return;
    }
    fetch(SERVERCONFIG.BASEURL + '/api/Accounts/clearHearingTests?access_token=' + state.user.accessToken.id, {
    method: 'POST',
    headers: SERVERCONFIG.HEADERS
    })
    .then(response => {
    console.log('here is your response', response);
    if (response.status !== 200) {
    throw new Error('Something is wrong');
    }
    return response.json()
    })


    the second method is called with



    export const deleteSingleHearingTest = (hearingTestNumber) => {
    return (dispatch, getState) => {
    let state = getState();
    if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
    console.debug('writeTestResult', state.user);
    // TODO: ERROR
    return;
    }
    console.log('single delete ', SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id)
    fetch(SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id, {
    method: 'POST',
    headers: SERVERCONFIG.HEADERS,
    body: JSON.stringify({ "hearingTestId": hearingTestNumber })


    })
    .then(response => {
    console.log('getting response from initial fetch inside deleteSingleReqport', response);


    They are nearly identical, however, one works..the other fails. What are some possible causes for the 401?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I created two custom endpoints with Loopback.



      Account.deleteAllHearingTests = function (req, callback) {
      console.log('here comes the req to delete all hearing tests', req);
      Account.findById(req.accessToken.userId)
      .then(account => {
      if (!account) {
      throw new Error('cannot find user');
      }
      return app.models.HearingTest.updateAll({ accountId: account.id }, { isDeleted: new Date() });
      })
      .then(() => {
      callback(null);
      })
      .catch(error => {
      callback(error);
      })
      }
      Account.remoteMethod(
      'deleteAllHearingTests', {
      http: {
      path: '/clearHearingTests',
      verb: 'post'
      },
      accepts: [
      { arg: 'req', type: 'object', http: { source: 'req' } }
      ],
      returns: {}
      }
      );


      the second one looks like this.



      Account.deleteSingleHearingTest = function (req, callback) {
      // console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
      Account.findById(req.accessToken.userId)
      .then(account => {
      if (!account) {
      throw new Error('Cannot find user');
      }
      console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
      return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });

      })
      .then(() => {
      callback(null);
      })
      .catch(error => {
      callback(error);
      });
      }

      Account.remoteMethod(
      'deleteSingleHearingTest', {
      http: {
      path: '/deleteSingleHearingTest',
      verb: 'post'
      },
      accepts: [
      { arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
      ],
      description: 'this is the end point for a single delete',
      returns: {}
      }
      );

      };


      The first custom method returns a 401 status response when I make the initial fetch. The second returns a 200.



      Inside my actions file the first method is called with something that looks like this:



      export function deleteAllHearingTests() {
      return (dispatch, getState) => {
      let state = getState();
      if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
      console.debug('deleteAllHearingTests', state.user);
      // TODO: ERROR
      return;
      }
      fetch(SERVERCONFIG.BASEURL + '/api/Accounts/clearHearingTests?access_token=' + state.user.accessToken.id, {
      method: 'POST',
      headers: SERVERCONFIG.HEADERS
      })
      .then(response => {
      console.log('here is your response', response);
      if (response.status !== 200) {
      throw new Error('Something is wrong');
      }
      return response.json()
      })


      the second method is called with



      export const deleteSingleHearingTest = (hearingTestNumber) => {
      return (dispatch, getState) => {
      let state = getState();
      if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
      console.debug('writeTestResult', state.user);
      // TODO: ERROR
      return;
      }
      console.log('single delete ', SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id)
      fetch(SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id, {
      method: 'POST',
      headers: SERVERCONFIG.HEADERS,
      body: JSON.stringify({ "hearingTestId": hearingTestNumber })


      })
      .then(response => {
      console.log('getting response from initial fetch inside deleteSingleReqport', response);


      They are nearly identical, however, one works..the other fails. What are some possible causes for the 401?










      share|improve this question













      I created two custom endpoints with Loopback.



      Account.deleteAllHearingTests = function (req, callback) {
      console.log('here comes the req to delete all hearing tests', req);
      Account.findById(req.accessToken.userId)
      .then(account => {
      if (!account) {
      throw new Error('cannot find user');
      }
      return app.models.HearingTest.updateAll({ accountId: account.id }, { isDeleted: new Date() });
      })
      .then(() => {
      callback(null);
      })
      .catch(error => {
      callback(error);
      })
      }
      Account.remoteMethod(
      'deleteAllHearingTests', {
      http: {
      path: '/clearHearingTests',
      verb: 'post'
      },
      accepts: [
      { arg: 'req', type: 'object', http: { source: 'req' } }
      ],
      returns: {}
      }
      );


      the second one looks like this.



      Account.deleteSingleHearingTest = function (req, callback) {
      // console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
      Account.findById(req.accessToken.userId)
      .then(account => {
      if (!account) {
      throw new Error('Cannot find user');
      }
      console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
      return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });

      })
      .then(() => {
      callback(null);
      })
      .catch(error => {
      callback(error);
      });
      }

      Account.remoteMethod(
      'deleteSingleHearingTest', {
      http: {
      path: '/deleteSingleHearingTest',
      verb: 'post'
      },
      accepts: [
      { arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
      ],
      description: 'this is the end point for a single delete',
      returns: {}
      }
      );

      };


      The first custom method returns a 401 status response when I make the initial fetch. The second returns a 200.



      Inside my actions file the first method is called with something that looks like this:



      export function deleteAllHearingTests() {
      return (dispatch, getState) => {
      let state = getState();
      if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
      console.debug('deleteAllHearingTests', state.user);
      // TODO: ERROR
      return;
      }
      fetch(SERVERCONFIG.BASEURL + '/api/Accounts/clearHearingTests?access_token=' + state.user.accessToken.id, {
      method: 'POST',
      headers: SERVERCONFIG.HEADERS
      })
      .then(response => {
      console.log('here is your response', response);
      if (response.status !== 200) {
      throw new Error('Something is wrong');
      }
      return response.json()
      })


      the second method is called with



      export const deleteSingleHearingTest = (hearingTestNumber) => {
      return (dispatch, getState) => {
      let state = getState();
      if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
      console.debug('writeTestResult', state.user);
      // TODO: ERROR
      return;
      }
      console.log('single delete ', SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id)
      fetch(SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id, {
      method: 'POST',
      headers: SERVERCONFIG.HEADERS,
      body: JSON.stringify({ "hearingTestId": hearingTestNumber })


      })
      .then(response => {
      console.log('getting response from initial fetch inside deleteSingleReqport', response);


      They are nearly identical, however, one works..the other fails. What are some possible causes for the 401?







      react-native redux fetch loopbackjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 at 13:28









      VK1

      17613




      17613
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          Did you try to call those methods with external tool like a postman, so you would exactly know if you don't miss access_token or something else? Also, when you compare code from one function and another, you can see that you are colling the updateAll with different arguments. It's hard to say without original code, but maybe the issue is there? Compare below:



          return app.models.HearingTest.updateAll(
          { accountId: account.id },
          { isDeleted: new Date() });

          return app.models.HearingTest.updateAll(
          { accountId: account.id, id: req.body.hearingTestId },
          { isDeleted: new Date() });


          Additionally, in fetch method they are also diffferences, you are missing in one case the below:



              body: JSON.stringify({ "hearingTestId": hearingTestNumber })


          What you could also do to debug and to provide more data is to run server in debug mode by calling:



          export DEBUG=*; npm start





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394064%2ftwo-custom-methods-endpoints-using-loopback-one-works-the-other-gives-a-401%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            Did you try to call those methods with external tool like a postman, so you would exactly know if you don't miss access_token or something else? Also, when you compare code from one function and another, you can see that you are colling the updateAll with different arguments. It's hard to say without original code, but maybe the issue is there? Compare below:



            return app.models.HearingTest.updateAll(
            { accountId: account.id },
            { isDeleted: new Date() });

            return app.models.HearingTest.updateAll(
            { accountId: account.id, id: req.body.hearingTestId },
            { isDeleted: new Date() });


            Additionally, in fetch method they are also diffferences, you are missing in one case the below:



                body: JSON.stringify({ "hearingTestId": hearingTestNumber })


            What you could also do to debug and to provide more data is to run server in debug mode by calling:



            export DEBUG=*; npm start





            share|improve this answer

























              up vote
              0
              down vote













              Did you try to call those methods with external tool like a postman, so you would exactly know if you don't miss access_token or something else? Also, when you compare code from one function and another, you can see that you are colling the updateAll with different arguments. It's hard to say without original code, but maybe the issue is there? Compare below:



              return app.models.HearingTest.updateAll(
              { accountId: account.id },
              { isDeleted: new Date() });

              return app.models.HearingTest.updateAll(
              { accountId: account.id, id: req.body.hearingTestId },
              { isDeleted: new Date() });


              Additionally, in fetch method they are also diffferences, you are missing in one case the below:



                  body: JSON.stringify({ "hearingTestId": hearingTestNumber })


              What you could also do to debug and to provide more data is to run server in debug mode by calling:



              export DEBUG=*; npm start





              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                Did you try to call those methods with external tool like a postman, so you would exactly know if you don't miss access_token or something else? Also, when you compare code from one function and another, you can see that you are colling the updateAll with different arguments. It's hard to say without original code, but maybe the issue is there? Compare below:



                return app.models.HearingTest.updateAll(
                { accountId: account.id },
                { isDeleted: new Date() });

                return app.models.HearingTest.updateAll(
                { accountId: account.id, id: req.body.hearingTestId },
                { isDeleted: new Date() });


                Additionally, in fetch method they are also diffferences, you are missing in one case the below:



                    body: JSON.stringify({ "hearingTestId": hearingTestNumber })


                What you could also do to debug and to provide more data is to run server in debug mode by calling:



                export DEBUG=*; npm start





                share|improve this answer












                Did you try to call those methods with external tool like a postman, so you would exactly know if you don't miss access_token or something else? Also, when you compare code from one function and another, you can see that you are colling the updateAll with different arguments. It's hard to say without original code, but maybe the issue is there? Compare below:



                return app.models.HearingTest.updateAll(
                { accountId: account.id },
                { isDeleted: new Date() });

                return app.models.HearingTest.updateAll(
                { accountId: account.id, id: req.body.hearingTestId },
                { isDeleted: new Date() });


                Additionally, in fetch method they are also diffferences, you are missing in one case the below:



                    body: JSON.stringify({ "hearingTestId": hearingTestNumber })


                What you could also do to debug and to provide more data is to run server in debug mode by calling:



                export DEBUG=*; npm start






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 20 at 16:48









                akkonrad

                11813




                11813






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394064%2ftwo-custom-methods-endpoints-using-loopback-one-works-the-other-gives-a-401%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python