使用 axios 拦截器引用令牌实现

时间:2021-07-30 17:47:47

标签: reactjs axios jwt refresh-token

我想通过在访问令牌到期后为每个请求发出发布请求来从刷新令牌中获取新的访问令牌。我已经使用 axios 拦截器实现了它,但在 api/notes/create/ 端点处的每个发布请求后都会收到 401 未经授权的错误。

要在 api/notes/create/ 上成功发布请求,我需要进行哪些更改?

export const Main = () => {
    const [showAddNote, setShowAddNote] = useState(false)
    const [notes, setNotes] = useState([])
    
    useEffect(()=>{
        const getNotes = () => {
            axios.get(`http://127.0.0.1:8000/api/notes/`)
            .then((res)=>{ setNotes(res.data)})
            .catch(err=>console.log(err))
        }
        
        getNotes()
    },[])

    axios.interceptors.response.use(undefined,         
      function axiosRetryInspector(err)  {
          const refreshToken = localStorage.getItem('refresh')
          if (err.response.status === 401 && err.response.data.detail === 'Authentication credentials were not provided.') {
            console.log("ooo")
            axios.post(`http://localhost:8000/api/accounts/token/refresh/`, {
              refresh: refreshToken
            })
              .then((res) => res.data)
              .then((res) => {
                console.log(err.config)
                err.config.headers['Authorization'] = 'Bearer ' + res.access;
                localStorage.setItem('access', res.access)

              })
          }
    
          return Promise.reject(err)
        }            
      );
      
    
      const addNote = (note) => {
        console.log("fffffff")        
        const headers = { 
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('access')
        }
        console.log(headers)
        axios.post(`http://127.0.0.1:8000/api/notes/create/`, note, { headers } )
        .then(res=> res.json())
        .catch(err=>console.log(err))
        
        setNotes([...notes, note])
    }
    
    return (
        <div>
            <Header />
            <CreateArea onAdd={addNote} />
            <Notes notes={notes} />
            <Footer />
        </div>
    )
}

0 个答案:

没有答案