【问题标题】:http://localhost:8000/token/ 400 (Bad Request)http://localhost:8000/token/ 400(错误请求)
【发布时间】:2022-01-21 09:15:20
【问题描述】:

在 django 中,我有 drf 的 jwt 模块(称为 simple-jwt),我已经按照文档中的说明设置了 url,如何在后端修复错误,整个登录过程应该是 POST 请求: urls.py

urlpatterns = [
    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

现在是反应部分(前端):

function Login(){
    let [login,setLogin] = useState({
        email: '',
        password:''

    });
    let cookie = Cookies.get('csrftoken');
    const { email, password } = login;
    function handleChange(e){
        console.log(e.target.value);
        setLogin({
            ...login,
            [e.target.name]: e.target.value
        });

    }
    function handleSubmit(e){
        const token = localStorage.getItem('token');
        e.preventDefault();
        axios.post('http://localhost:8000/token/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*','Authorization': `Bearer ${token}`}})
        .then(res => {
            console.log(res.data);
        }

        )
        .catch(err => console.log(err))
    }

    
    return (
        <div className="container">
        <form method='post' onSubmit={handleSubmit}>
            <h1>Login</h1>
            <label>
                Email:
                <input type='text' name = 'email' value={email} onChange={e=>handleChange(e)} required/>

            </label>
            <label>
                Password:
                <input type='password' name = 'password' value={password} onChange={e=>handleChange(e)} required/>
            </label>
            {isLoggedin = true}
            <button type='submit'>Login</button>
        </form>
            <p className='mt-3'>
                Don't have an Account? <Link to='/signup'>Sign Up</Link>
            </p>
        </div>
    );
};



export default Login;
``` this is login component, I am getting bad request (400) error, but I cant find out why, and how to fix it? if there is anything else (more code, or more information) to add, please do not be shy to tell me, thanks!

【问题讨论】:

    标签: javascript python reactjs django


    【解决方案1】:

    Django 400 错误请求是由多种原因引起的,包括语法错误、扩展损坏、URL 错误等。 您可以尝试以下步骤:

    1. 可能是 ALLOWED_HOSTS 变量设置不正确: 确保ALLOWED_HOSTS = ['127.0.0.1', 'localhost'],因为您在本地工作。

    2. 清除缓存以修复 400 bad request 错误。缓存也会产生问题,清除缓存并尝试检查错误是否消失。

    3. 这也可能是由损坏的扩展程序引起的,请注意您使用的已安装扩展程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多