Node.js使用passport-local在Postman中成功运行,但在Vue.js前端中出现问题
                
             
            
            
                <p>我正在使用passport-local进行用户身份验证。当我尝试获取已登录用户时,在postman中可以正常工作,但会显示我设置的错误消息“您需要先登录才能获取数据”。我的用户可以成功从vue js登录,但当我尝试获取已登录用户时,会显示我的错误消息。</p>
<p>这是我的路由:</p>
<pre class="brush:php;toolbar:false;">router.get('/jobs', auth ,async(req, res) => {
    const jobs = await Job.find({}).sort({
      createdAt : -1
   })
   console.log(req.user)//这在postman中可以工作,但在vue js中会出错
   res.send(jobs)
})</pre>
<p>我正在使用cors,并指定origin并将credentials设置为true。</p>
<p>这是我的前端请求:</p>
<pre class="brush:php;toolbar:false;">try{ 
          const res = await axios.get('http://localhost:3000/jobs', {
            withCredentials : true
          })
          this.jobs = await res.data
          console.log(this.jobs) // 即使我已登录,它也会显示我的错误消息
        }catch(error) {
           if(error.response) {
               this.message = error.response.data
           }
        }</pre></p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
     
如果您使用令牌,您需要在请求中传递它,就像这样:
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) // 即使我已经登录,它也会给我错误消息 }catch(error) { if(error.response) { this.message = error.response.data } }在Postman中查看您发送的标题。
编辑:添加了图片