Express.js Unauthorized error










0















I have method



router.post('/user',passport.authenticate('jwt', session: false ), function (request, res) 
res.send(request.user);
);


and authorization token



"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"


when i send request to this route from postman everything is working.



but when i send request from angular application with same token its throw with error unauthorized



 getUser() 
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
return this.http.post('localhost:8000/api/user/',
headers
)
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));










share|improve this question
























  • Check the headers once.

    – Shubham
    Jun 7 '17 at 10:42











  • can you share the angular code snippet without it no one will be able to help.

    – warl0ck
    Jun 7 '17 at 10:43











  • @Shubham i check headers token is the same

    – Aliaga Aliyev
    Jun 7 '17 at 10:45











  • are you using ionic ? or is this local storage the browser's local storage ?

    – warl0ck
    Jun 7 '17 at 10:51















0















I have method



router.post('/user',passport.authenticate('jwt', session: false ), function (request, res) 
res.send(request.user);
);


and authorization token



"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"


when i send request to this route from postman everything is working.



but when i send request from angular application with same token its throw with error unauthorized



 getUser() 
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
return this.http.post('localhost:8000/api/user/',
headers
)
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));










share|improve this question
























  • Check the headers once.

    – Shubham
    Jun 7 '17 at 10:42











  • can you share the angular code snippet without it no one will be able to help.

    – warl0ck
    Jun 7 '17 at 10:43











  • @Shubham i check headers token is the same

    – Aliaga Aliyev
    Jun 7 '17 at 10:45











  • are you using ionic ? or is this local storage the browser's local storage ?

    – warl0ck
    Jun 7 '17 at 10:51













0












0








0








I have method



router.post('/user',passport.authenticate('jwt', session: false ), function (request, res) 
res.send(request.user);
);


and authorization token



"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"


when i send request to this route from postman everything is working.



but when i send request from angular application with same token its throw with error unauthorized



 getUser() 
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
return this.http.post('localhost:8000/api/user/',
headers
)
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));










share|improve this question
















I have method



router.post('/user',passport.authenticate('jwt', session: false ), function (request, res) 
res.send(request.user);
);


and authorization token



"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"


when i send request to this route from postman everything is working.



but when i send request from angular application with same token its throw with error unauthorized



 getUser() 
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
return this.http.post('localhost:8000/api/user/',
headers
)
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));







javascript angularjs node.js express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 7 '17 at 13:28







Aliaga Aliyev

















asked Jun 7 '17 at 10:40









Aliaga AliyevAliaga Aliyev

18315




18315












  • Check the headers once.

    – Shubham
    Jun 7 '17 at 10:42











  • can you share the angular code snippet without it no one will be able to help.

    – warl0ck
    Jun 7 '17 at 10:43











  • @Shubham i check headers token is the same

    – Aliaga Aliyev
    Jun 7 '17 at 10:45











  • are you using ionic ? or is this local storage the browser's local storage ?

    – warl0ck
    Jun 7 '17 at 10:51

















  • Check the headers once.

    – Shubham
    Jun 7 '17 at 10:42











  • can you share the angular code snippet without it no one will be able to help.

    – warl0ck
    Jun 7 '17 at 10:43











  • @Shubham i check headers token is the same

    – Aliaga Aliyev
    Jun 7 '17 at 10:45











  • are you using ionic ? or is this local storage the browser's local storage ?

    – warl0ck
    Jun 7 '17 at 10:51
















Check the headers once.

– Shubham
Jun 7 '17 at 10:42





Check the headers once.

– Shubham
Jun 7 '17 at 10:42













can you share the angular code snippet without it no one will be able to help.

– warl0ck
Jun 7 '17 at 10:43





can you share the angular code snippet without it no one will be able to help.

– warl0ck
Jun 7 '17 at 10:43













@Shubham i check headers token is the same

– Aliaga Aliyev
Jun 7 '17 at 10:45





@Shubham i check headers token is the same

– Aliaga Aliyev
Jun 7 '17 at 10:45













are you using ionic ? or is this local storage the browser's local storage ?

– warl0ck
Jun 7 '17 at 10:51





are you using ionic ? or is this local storage the browser's local storage ?

– warl0ck
Jun 7 '17 at 10:51












2 Answers
2






active

oldest

votes


















0














Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.



your code will be like:



import Http, Headers, RequestOptions from '@angular/http';
getUser()
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
let options = new RequestOptions( headers: headers );
return this.http.post('https://dropali.com/api/user/',options)
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));



Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.






share|improve this answer























  • I wrap headers to RequestOptions but same result

    – Aliaga Aliyev
    Jun 7 '17 at 11:01











  • is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

    – warl0ck
    Jun 7 '17 at 11:02











  • no it is not ionic app it is angular 4

    – Aliaga Aliyev
    Jun 7 '17 at 11:17











  • this is browsers's localstorage

    – Aliaga Aliyev
    Jun 7 '17 at 11:18











  • have you tried printing the header token to check your are getting one in your post request

    – warl0ck
    Jun 7 '17 at 11:32


















0














1.) Check at the server side you are getting the token or not.
2.) if you are not getting the token then check Developer option > Network > your request's header tag and see whether the token is going or not
3.) if not going the problem is in a front and else it can because of cross origin..



FRONT END CODE EXAMPLE



 var token = localStorage.Authorization 
var options =
url: '/user',
method: 'POST',
headers:
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': token


$http(options)
.then((data) => console.log(data.data))
.catch((error) => console.log(error));


if front end is ok then you should check CROSS



app.use((req, res, next) => 
res.header('Access-Control-Expose-Headers', 'Authorization');
next();
)


OR



npm install cors --save
app.use(cors());





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',
    autoActivateHeartbeat: false,
    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%2f44410381%2fexpress-js-unauthorized-error%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.



    your code will be like:



    import Http, Headers, RequestOptions from '@angular/http';
    getUser()
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    let options = new RequestOptions( headers: headers );
    return this.http.post('https://dropali.com/api/user/',options)
    .map((data: Response) => data.json())
    .catch((error: Response) => Observable.throw(error.json()));



    Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.






    share|improve this answer























    • I wrap headers to RequestOptions but same result

      – Aliaga Aliyev
      Jun 7 '17 at 11:01











    • is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

      – warl0ck
      Jun 7 '17 at 11:02











    • no it is not ionic app it is angular 4

      – Aliaga Aliyev
      Jun 7 '17 at 11:17











    • this is browsers's localstorage

      – Aliaga Aliyev
      Jun 7 '17 at 11:18











    • have you tried printing the header token to check your are getting one in your post request

      – warl0ck
      Jun 7 '17 at 11:32















    0














    Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.



    your code will be like:



    import Http, Headers, RequestOptions from '@angular/http';
    getUser()
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    let options = new RequestOptions( headers: headers );
    return this.http.post('https://dropali.com/api/user/',options)
    .map((data: Response) => data.json())
    .catch((error: Response) => Observable.throw(error.json()));



    Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.






    share|improve this answer























    • I wrap headers to RequestOptions but same result

      – Aliaga Aliyev
      Jun 7 '17 at 11:01











    • is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

      – warl0ck
      Jun 7 '17 at 11:02











    • no it is not ionic app it is angular 4

      – Aliaga Aliyev
      Jun 7 '17 at 11:17











    • this is browsers's localstorage

      – Aliaga Aliyev
      Jun 7 '17 at 11:18











    • have you tried printing the header token to check your are getting one in your post request

      – warl0ck
      Jun 7 '17 at 11:32













    0












    0








    0







    Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.



    your code will be like:



    import Http, Headers, RequestOptions from '@angular/http';
    getUser()
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    let options = new RequestOptions( headers: headers );
    return this.http.post('https://dropali.com/api/user/',options)
    .map((data: Response) => data.json())
    .catch((error: Response) => Observable.throw(error.json()));



    Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.






    share|improve this answer













    Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.



    your code will be like:



    import Http, Headers, RequestOptions from '@angular/http';
    getUser()
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    let options = new RequestOptions( headers: headers );
    return this.http.post('https://dropali.com/api/user/',options)
    .map((data: Response) => data.json())
    .catch((error: Response) => Observable.throw(error.json()));



    Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 7 '17 at 10:55









    warl0ckwarl0ck

    1,41511431




    1,41511431












    • I wrap headers to RequestOptions but same result

      – Aliaga Aliyev
      Jun 7 '17 at 11:01











    • is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

      – warl0ck
      Jun 7 '17 at 11:02











    • no it is not ionic app it is angular 4

      – Aliaga Aliyev
      Jun 7 '17 at 11:17











    • this is browsers's localstorage

      – Aliaga Aliyev
      Jun 7 '17 at 11:18











    • have you tried printing the header token to check your are getting one in your post request

      – warl0ck
      Jun 7 '17 at 11:32

















    • I wrap headers to RequestOptions but same result

      – Aliaga Aliyev
      Jun 7 '17 at 11:01











    • is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

      – warl0ck
      Jun 7 '17 at 11:02











    • no it is not ionic app it is angular 4

      – Aliaga Aliyev
      Jun 7 '17 at 11:17











    • this is browsers's localstorage

      – Aliaga Aliyev
      Jun 7 '17 at 11:18











    • have you tried printing the header token to check your are getting one in your post request

      – warl0ck
      Jun 7 '17 at 11:32
















    I wrap headers to RequestOptions but same result

    – Aliaga Aliyev
    Jun 7 '17 at 11:01





    I wrap headers to RequestOptions but same result

    – Aliaga Aliyev
    Jun 7 '17 at 11:01













    is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

    – warl0ck
    Jun 7 '17 at 11:02





    is it that the localstorage your are refereeing here is from the ionic app's localstorage i.e. this code snippet is of ionic app ?

    – warl0ck
    Jun 7 '17 at 11:02













    no it is not ionic app it is angular 4

    – Aliaga Aliyev
    Jun 7 '17 at 11:17





    no it is not ionic app it is angular 4

    – Aliaga Aliyev
    Jun 7 '17 at 11:17













    this is browsers's localstorage

    – Aliaga Aliyev
    Jun 7 '17 at 11:18





    this is browsers's localstorage

    – Aliaga Aliyev
    Jun 7 '17 at 11:18













    have you tried printing the header token to check your are getting one in your post request

    – warl0ck
    Jun 7 '17 at 11:32





    have you tried printing the header token to check your are getting one in your post request

    – warl0ck
    Jun 7 '17 at 11:32













    0














    1.) Check at the server side you are getting the token or not.
    2.) if you are not getting the token then check Developer option > Network > your request's header tag and see whether the token is going or not
    3.) if not going the problem is in a front and else it can because of cross origin..



    FRONT END CODE EXAMPLE



     var token = localStorage.Authorization 
    var options =
    url: '/user',
    method: 'POST',
    headers:
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': token


    $http(options)
    .then((data) => console.log(data.data))
    .catch((error) => console.log(error));


    if front end is ok then you should check CROSS



    app.use((req, res, next) => 
    res.header('Access-Control-Expose-Headers', 'Authorization');
    next();
    )


    OR



    npm install cors --save
    app.use(cors());





    share|improve this answer





























      0














      1.) Check at the server side you are getting the token or not.
      2.) if you are not getting the token then check Developer option > Network > your request's header tag and see whether the token is going or not
      3.) if not going the problem is in a front and else it can because of cross origin..



      FRONT END CODE EXAMPLE



       var token = localStorage.Authorization 
      var options =
      url: '/user',
      method: 'POST',
      headers:
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': token


      $http(options)
      .then((data) => console.log(data.data))
      .catch((error) => console.log(error));


      if front end is ok then you should check CROSS



      app.use((req, res, next) => 
      res.header('Access-Control-Expose-Headers', 'Authorization');
      next();
      )


      OR



      npm install cors --save
      app.use(cors());





      share|improve this answer



























        0












        0








        0







        1.) Check at the server side you are getting the token or not.
        2.) if you are not getting the token then check Developer option > Network > your request's header tag and see whether the token is going or not
        3.) if not going the problem is in a front and else it can because of cross origin..



        FRONT END CODE EXAMPLE



         var token = localStorage.Authorization 
        var options =
        url: '/user',
        method: 'POST',
        headers:
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token


        $http(options)
        .then((data) => console.log(data.data))
        .catch((error) => console.log(error));


        if front end is ok then you should check CROSS



        app.use((req, res, next) => 
        res.header('Access-Control-Expose-Headers', 'Authorization');
        next();
        )


        OR



        npm install cors --save
        app.use(cors());





        share|improve this answer















        1.) Check at the server side you are getting the token or not.
        2.) if you are not getting the token then check Developer option > Network > your request's header tag and see whether the token is going or not
        3.) if not going the problem is in a front and else it can because of cross origin..



        FRONT END CODE EXAMPLE



         var token = localStorage.Authorization 
        var options =
        url: '/user',
        method: 'POST',
        headers:
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token


        $http(options)
        .then((data) => console.log(data.data))
        .catch((error) => console.log(error));


        if front end is ok then you should check CROSS



        app.use((req, res, next) => 
        res.header('Access-Control-Expose-Headers', 'Authorization');
        next();
        )


        OR



        npm install cors --save
        app.use(cors());






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 13 '18 at 10:05









        slashburn

        2,26212141




        2,26212141










        answered Jun 9 '17 at 13:28









        Shivam MishraShivam Mishra

        643159




        643159



























            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44410381%2fexpress-js-unauthorized-error%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







            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3