简体   繁体   English

Python 请求 POST 和 axios POST 之间的区别

[英]Difference between Python requests POST and axios POST

I am having a difficult time understanding why my API call does not work in axios (relatively new to JS).我很难理解为什么我的 API 调用在axios (JS 相对较新)中不起作用。 I have built an API server that takes in an Authorization header with a JWT token.我已经构建了一个 API 服务器,该服务器使用 JWT 令牌接受Authorization header。

Here is my POST request workflow in Python:这是我在 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

Using axios :使用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...

What is different about the two above requests?上述两个请求有什么不同? Why does the axios version return different results than requests?为什么axios版本返回的结果与请求不同?

In my API, CORS have been set to * , and I know that the token within Axios is being saved properly in sessionStorage .在我的 API 中,CORS 已设置为* ,我知道 Axios 中的token已正确保存在sessionStorage中。

Any ideas?有任何想法吗?

As far as I can see you are passing your username and password in axios as params and as body data in your python request, I am not sure if your backend expects it as params or body data but try changing const params = new URLSearchParams();据我所见,您将 axios 中的用户名和密码作为参数和 python 请求中的正文数据传递,我不确定您的后端是否期望它作为参数或正文数据,但尝试更改const params = new URLSearchParams(); to const params = new FormData(); to const params = new FormData(); if the problem is that the backend isn't getting the body data it needs.如果问题是后端没有获得它需要的正文数据。 The best thing I could recommend is checking your browser network tab and seeing what exactly the problem is when you hit your server.我可以推荐的最好的事情是检查您的浏览器网络选项卡,看看当您访问您的服务器时究竟是什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM