簡體   English   中英

Python 請求 POST 和 axios POST 之間的區別

[英]Difference between Python requests POST and axios POST

我很難理解為什么我的 API 調用在axios (JS 相對較新)中不起作用。 我已經構建了一個 API 服務器,該服務器使用 JWT 令牌接受Authorization header。

這是我在 Python 中的 POST 請求工作流程:

resp = requests.post('http://127.0.0.1:8000/api/v1/login/access-token', data={'username': 'admin@xyz.com', 'password': 'password'})
token = resp.json()['access_token']

test = requests.post('http://127.0.0.1:8000/api/v1/login/test-token', headers={'Authorization': f'Bearer {token}'})
# ALL SUCCESSFUL

使用axios

  const handleLogin = () => {
    const params = new URLSearchParams();
    params.append('username', username.value);
    params.append('password', password.value);
    setError(null);
    setLoading(true);
    axios.post('http://localhost:8000/api/v1/login/access-token', params).then(response => {
      console.log(response)
      setLoading(false);
      setUserSession(response.data.access_token);
      props.history.push('/dashboard');
    }).catch(error => {
      setLoading(false);
      console.log(error.response)
      if (error.response.status === 401) {
        setError(error.response.data.message);
      } else {
        setError("Something went wrong. Please try again later.");
      }
    });
  }
// the above works fine

// however:
  const [authLoading, setAuthLoading] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) {
      return;
    }

    axios.post(`http://localhost:8000/api/v1/login/test-token`, {
      headers: {
        'Authorization': 'Bearer ' + token
      }
    }).then(response => {
      // setUserSession(response.data.token);
      console.log('we made it')
      setAuthLoading(false);
    }).catch(error => {
      removeUserSession();
      setAuthLoading(false);
    });
  }, []);

  if (authLoading && getToken()) {
    return <div className="content">Checking Authentication...</div>
  }
// RETURNS A 401 Unauthorized response...

上述兩個請求有什么不同? 為什么axios版本返回的結果與請求不同?

在我的 API 中,CORS 已設置為* ,我知道 Axios 中的token已正確保存在sessionStorage中。

有任何想法嗎?

據我所見,您將 axios 中的用戶名和密碼作為參數和 python 請求中的正文數據傳遞,我不確定您的后端是否期望它作為參數或正文數據,但嘗試更改const params = new URLSearchParams(); to const params = new FormData(); 如果問題是后端沒有獲得它需要的正文數據。 我可以推薦的最好的事情是檢查您的瀏覽器網絡選項卡,看看當您訪問您的服務器時究竟是什么問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM