繁体   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