reactjs 如何在React中使用JWT标记将带有user_id字段的表单数据保存到数据库中?

ilmyapht  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(108)

我正在使用Django、Django-Rest-API、React和Axios。
我试图使youtube克隆网络应用程序。所以我做了一个创建的形式与标题,描述,视频和图像字段。我需要添加用户ID字段。
它假定获取JWT标记,并将其用作user字段中的user_id。
JWT token of the glebapetenok@gmail.com user
此文件是关于视频创建表单。

// ...
// frontend/src/components/admin/create.js
import React, { useState } from 'react';
import axiosInstance from '../../axios';
import { useHistory } from 'react-router-dom';

export default function Create() {
    const history = useHistory();
    const initialFormData = Object.freeze({
        title: '',
        description: '',
    });

    const [videoData, updateFormData] = useState(initialFormData);
    const [videoimage, setVideoImage] = useState(null);
    const [videovideo, setVideoVideo] = useState(null);

    const handleChange = (e) => {
        if ([e.target.name] == 'image') {
            setVideoImage({
                image: e.target.files,
            });
            console.log(e.target.files);
        }
        if ([e.target.name] == 'video') {
            setVideoVideo({
                video: e.target.files,
            });
            console.log(e.target.files);
        }
        if ([e.target.name] == 'title') {
            updateFormData({
                ...videoData,
                [e.target.name]: e.target.value.trim(),
            });
        } else {
            updateFormData({
                ...videoData,
                [e.target.name]: e.target.value.trim(),
            });
        }
    };
    

    const handleSubmit = (e) => {
        const config = { headers: { 'Content-Type': 'multipart/form-data' } };
        const URL = 'http://127.0.0.1:8000/api/admin/create/';
        let formData = new FormData();
        formData.append('title', videoData.title);

        // default user_id seted to 1
        formData.append('user', 1);

        formData.append('description', videoData.description);
        formData.append('image', videoimage.image[0]);
        formData.append('video', videovideo.video[0]);
        axios
            .post(URL, formData, config)
            .then((res) => {
                console.log(res.data);
            })
            .catch((err) => console.log(err));
    };

下面是前端文件夹中包含JWT设置的API文件

// frontend/src/axios.js
import axios from 'axios';

const baseURL = 'http://127.0.0.1:8000/api/';

const axiosInstance = axios.create({
    baseURL: baseURL,
    timeout: 5000,
    headers: {
        Authorization: localStorage.getItem('access_token')
            ? 'JWT ' + localStorage.getItem('access_token')
            : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    },
});

axiosInstance.interceptors.response.use(
    (response) => {
        return response;
    },
    async function (error) {
        const originalRequest = error.config;

        if (typeof error.response === 'undefined') {
            alert(
                'A server/network error occurred. ' +
                    'Looks like CORS might be the problem. ' +
                    'Sorry about this - we will get it fixed shortly.'
            );
            return Promise.reject(error);
        }

        if (
            error.response.status === 401 &&
            originalRequest.url === baseURL + 'token/refresh/'
        ) {
            window.location.href = '/login/';
            return Promise.reject(error);
        }

        if (
            error.response.data.code === 'token_not_valid' &&
            error.response.status === 401 &&
            error.response.statusText === 'Unauthorized'
        ) {
            const refreshToken = localStorage.getItem('refresh_token');

            if (refreshToken) {
                const tokenParts = JSON.parse(atob(refreshToken.split('.')[1]));

                // exp date in token is expressed in seconds, while now() returns milliseconds:
                const now = Math.ceil(Date.now() / 1000);
                console.log(tokenParts.exp);

                if (tokenParts.exp > now) {
                    return axiosInstance
                        .post('/token/refresh/', {
                            refresh: refreshToken,
                        })
                        .then((response) => {
                            localStorage.setItem('access_token', response.data.access);
                            localStorage.setItem('refresh_token', response.data.refresh);

                            axiosInstance.defaults.headers['Authorization'] =
                                'JWT ' + response.data.access;
                            originalRequest.headers['Authorization'] =
                                'JWT ' + response.data.access;

                            return axiosInstance(originalRequest);
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    console.log('Refresh token is expired', tokenParts.exp, now);
                    window.location.href = '/login/';
                }
            } else {
                console.log('Refresh token not available.');
                window.location.href = '/login/';
            }
        }

        // specific error handling done elsewhere
        return Promise.reject(error);
    }

);

export default axiosInstance;
ni65a41a

ni65a41a1#

我想您希望将带有用户ID字段的表单数据保存到数据库中。
由于表单数据属于当前登录的用户,因此您可以在后端API中执行此操作,而不是将user_id字段添加到Web页面中的表单。从api请求头lie axios headers:Authorization中获取JWT令牌非常容易。

相关问题