【问题标题】:React JS: problem in receiving cookie with axios, which is received from JWT DjangoReact JS:用 axios 接收 cookie 时出现问题,这是从 JWT Django 接收的
【发布时间】:2021-07-16 03:17:51
【问题描述】:

首先,我使用 Django 创建了一个 POST APIView 函数,并在其中添加了 JWT 令牌。这个 api 基本上是为登录目的而制作的。我可以传输其中的所有详细信息并收到一个 cookie 作为回报。

class LoginView(APIView):
   def post(self, request):
       email = request.data['email']
       password = request.data['password']

       user = User.objects.filter(email=email).first()

       if user is None:
           raise AuthenticationFailed('user not found')

       if not user.check_password(password):
           raise AuthenticationFailed('Incorrect password')

       payload = {
           'id': user.id,
           'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
           'iat': datetime.datetime.utcnow()
       }

       token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')

       response = Response()

       response.set_cookie(key='jwt', value=token, httponly=True)
       response.data = {
           'jwt': token
       }
       return response

我在 react js 中使用 axios 使用 POST 请求,并尝试在“withCredentials: true”的帮助下接收 cookie,但无法获取 cookie。

import React, { Component } from 'react';
import axios from 'axios';

class Login extends Component {
    state = {
        email: '',
        password: '',
    };

    handleSubmit(event){
        event.preventDefault();
        
        axios({
                method: 'post',
                url: 'http://127.0.0.1:8000/user/login ',
                withCredentials: true,
                data: {
                  email: this.state.email,
                  password: this.state.password
                }
              })
              .then(data => console.log(data));
    }


    handleChange(event){
        const target = event.target;
        const value = target.value;
        const name = target.name;
        this.setState({[name]:value})
    }


    render() {
        return (
            <div>
                <h1>LOGIN</h1>
                <form onSubmit={this.handleSubmit.bind(this)}>
          <div>
            <label>Email: </label>
            <br />
            <input
              type="text"
              name="email"
              onChange={this.handleChange.bind(this)}
              value={this.state.email}
            />
          </div>
          <br />
          <div>
            <label>Password: </label>
            <br />
            <input
              type="password"
              name="password"
              onChange={this.handleChange.bind(this)}
              value={this.state.password}
            />
          </div>
          <br />
          <button type="submit">Submit</button>
        </form>
                
            </div>
        );
    }
}

export default Login;

I am getting this issue in the console.

【问题讨论】:

  • 添加 samesite = 'Lax'response.set_cookie(key='jwt', value=token, httponly=True,samesite = 'Lax')
  • @Pradip 这个语法对我不起作用。 axios({ method: 'post', url: 'http://127.0.0.1:8000/user/login ', withCredentials: true, response.set-cookie(key='jwt', value=token, httponly=True,samesite = 'Lax'), data: { email: this.state.email, password: this.state.password } }) 和我收到错误“','预期。”

标签: reactjs django cookies axios jwt


【解决方案1】:

而不是使用 axios。我使用了对我有用的 fetch()。

        event.preventDefault();
        
            const response = await fetch('http://localhost:8000/user/login', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'include',
            body: JSON.stringify({
              email: this.state.email,
              password: this.state.password
            })
        });
        console.log(response)
    }```

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2021-05-15
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多