如何将当前用户ID添加到axios.get请求中?

ipakzgxi  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(189)

我如何在前端代码中将当前用户id添加到axios.get请求url中?
这是我的密码;
后端:urls.py

urlpatterns = [
    path('<int:pk>/', UserDetail.as_view()),
]

和views.py

class UserDetail(APIView):
    permission_classes = [AllowAny]
    http_method_names = ['get', 'head', 'post']
    """
    Retrieve, update or delete a user instance.
    """
    def get_object(self, pk):
        try:
            return NewUser.objects.get(pk=pk)
        except NewUser.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        user = self.get_object(pk)
        serializer = CustomUserSerializer(user)
        return Response(serializer.data)

前端:

useEffect(() => {
    if (localStorage.getItem("access_token")) {
      axiosInstance.get('users/**???**').then((obj) => {
       {
        setname(obj.username)
        setemail(obj.email)
        setidx(obj.uid)
        }
        console.log(obj);
        console.log(obj.data);
          setTimeout(() => {
          props.resetProfileFlag();
        }, 3000);
      }); 
    }

  }, [props.success])

如果我手动添加用户标识(比如说; axiosInstance.get('users/1').then((obj)=〉{...)它获取用户的详细信息。

bhmjp9jg

bhmjp9jg1#

在你的axios部分,你需要使用如下参数:

useEffect(() => {
    if (localStorage.getItem("access_token")) {
      axiosInstance.get('users/',
      {
      params: {
                id: '1'
              }
        }).then((obj) => {
       {
        setname(obj.username)
        setemail(obj.email)
        setidx(obj.uid)
        }
        console.log(obj);
        console.log(obj.data);
          setTimeout(() => {
          props.resetProfileFlag();
        }, 3000);
      }); 
    }

  }, [props.success])

而在后端,您也可以从request.params中获取数据。

6qfn3psc

6qfn3psc2#

谢谢Rassaka,但是,我仍然不能得到一个单一的用户的详细信息,但我得到了所有用户的数据在控制台的列表.
我转到了DRF视图集和超链接模型序列化程序:

class UserSerializer(serializers.HyperlinkedModelSerializer):
posts = serializers.HyperlinkedRelatedField(
    many=True, 
    queryset=Post.objects.all(),
    view_name='blog:post-detail',
)
url = serializers.HyperlinkedIdentityField(view_name='users:user-detail')

class Meta:
    model = User
    fields = ('url', 'id', 'user_name', 'email', 'posts')

views.py :

class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
permission_classes = [AllowAny]
queryset = User.objects.all()
serializer_class = UserSerializer

# lookup_field = 'pk'

def post(self, request):
    try:
        refresh_token = request.data["refresh_token"]
        token = RefreshToken(refresh_token)
        token.blacklist()
        return Response(status=status.HTTP_205_RESET_CONTENT)
    except Exception as e:
        return Response(status=status.HTTP_400_BAD_REQUEST)

urls.py:

urlpatterns = [

router.register(r'users/<int:pk>', views.UserViewSet),
router.register(r'users', views.UserViewSet),
] 
urlpatterns = [ re_path(r'^', include(router.urls)) ]

最后是我React前端:

const UserProfile = props => {  
  const [data, setData] = useState({
        users: [],
    });

  useEffect(() => {
    if (localStorage.getItem("access_token")) {
      axiosInstance.get('users/', {params: { id: '1'}}).then((res) => {
        setData({
          users: res.data,
        })
        console.log(res.data);
        setTimeout(() => {
          props.resetProfileFlag();
        }, 3000);
      })
      .catch(err =>{
        console.log(err)
      })
    }
  }, [setData], [props.success])

  return (
    <React.Fragment>
      <div className="page-content">
        <Container fluid>
          <Row>
            <Col lg="12">
              <Card>
                <CardBody>
                  <div className="d-flex">
                    <div className="ms-3"> 
                      <img
                        src={data.users.avatar}
                        alt=""
                        className="avatar-md rounded-circle img-thumbnail"
                      />
                    </div>
                    <div className="align-self-center flex-1">
                      <div className="text-muted">
                        <h5>Username: {data.users.user_name} {''}</h5>
                        <p className="mb-1">Email: {data.users.email} {''}</p>
                        <p className="mb-0">Id no: {data.users.id} {''}</p>
                      </div>
                    </div>
                  </div>
                </CardBody>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    </React.Fragment>
  )
}

export default UserProfile

问题是:登录后,我在控制台中获得了正确的用户数据,但是,当我进入用户配置文件页面时,首先,我收到错误消息“GET http://127.0.0.1:8000/api/users/?id=1 401(未授权)”。但在此之后,后端立即刷新令牌““POST /api/token/refresh/ HTTP/1.1”200”-〉“GET /api/users/?id=1 HTTP/1.1”200”。但是我在控制台中得到了所有的用户数组(数据)-(不是登录的用户数据),但是用户配置文件页面无法检索到任何用户数据。所以我不明白用户数据无法检索到配置文件页面是因为axiosInstanse在登录后刷新了令牌还是因为我的前端设计错误。还是后端有什么问题??请您提供建议?...

相关问题