首頁  >  問答  >  主體

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>
P粉170858678P粉170858678415 天前379

全部回覆(1)我來回復

  • P粉197639753

    P粉1976397532023-08-31 11:05:53

    如果您使用令牌,您需要在請求中傳遞它,就像這樣:

    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中查看您發送的標題。

    編輯:新增了圖片

    #

    回覆
    0
  • 取消回覆