Node js login using passport-local working in postman but getting error in frontend Vue JS

Viewed 196

I am using passport-local for user authentication. When I try to get logged in User it works in postman but gives error message which i set to "You need to be logged in first to get data". My user is successfully logging in from vue js but when i try to get logged in user its gives my error message.

here is my route :

router.get('/jobs', auth ,async(req, res) => {
    const jobs = await Job.find({}).sort({
      createdAt : -1
   })
   console.log(req.user)//This is working in postman but gives error in vue js
   res.send(jobs)
})

I am using cors and specifying origin and set credentials to true.

here is my frontend request :

 try{ 
          const res = await axios.get('http://localhost:3000/jobs', {
            withCredentials : true
          })

          this.jobs = await res.data
          console.log(this.jobs) // It gives my error message even i am logged in
        }catch(error) {
           if(error.response) {
               this.message = error.response.data
           }
        }
1 Answers

If you use token, you need to pass it with your request like that:

const config = {
      withCredentials : true,
      headers: { 
        Token: user.value.token 
      },
    };

     try{ 
          const res = await axios.get('http://localhost:3000/jobs', config)

          this.jobs = await res.data
          console.log(this.jobs) // It gives my error message even i am logged in
        }catch(error) {
           if(error.response) {
               this.message = error.response.data
           }
        }

Look in postman the headers you are sending.

edit: added image enter image description here

Related