Next Js - 如何从需要授权的api中检索数据(通过axios)?

Posted

技术标签:

【中文标题】Next Js - 如何从需要授权的api中检索数据(通过axios)?【英文标题】:Next Js - How to retrieve data from the api requiring authorization (via axios)? 【发布时间】:2022-01-12 10:02:13 【问题描述】:

enter image description here

user = Cookies.get("user")

我无法进入这条路。我使用 cookie 来存储用户数据,包括令牌。 请问我需要帮助

【问题讨论】:

请使用代码sn-ps,请勿使用图像进行代码。 【参考方案1】:

我认为您使用 Strapi CMS 和请求验证根的方法必须是 POST 而不是 GET 这里的示例:

const data ,status = await 
   axios.post('https://localhost:1337/posts',
       headers :  
           Authorization: `Bearer $token`
        
   );
 if(status === 200)
   setData(data)
  else
   console.log('eeror')
   

确保在strapi admin中标记find方法,否则你会在strapi user has jwt not token中得到403错误,所以确保token是用户登录时来自strpai的jwt!

【讨论】:

我遇到了 401 服务器错误 同时登录电子邮件的正文传递标识符 instrad,例如:const data = await axios.post('localhost:1337/auth/local', identifier: 'reader@strapi.io', password: 'strapi ', );

以上是关于Next Js - 如何从需要授权的api中检索数据(通过axios)?的主要内容,如果未能解决你的问题,请参考以下文章