发布请求中禁止(403)-djangorest-react

时间:2019-03-15 08:15:42

标签: python django reactjs api django-rest-framework

我有一个用于用户注册的端点。 我在项目的正面使用react。我将POST请求发送到具有json主体的端点以注册用户。 但返回的是“禁止的”(403)。 当我使用邮递员测试功能时,一切正常,但使用axios则不是。

错误:POST / user / register / 403(禁止)

端点:用户/注册/

注册API视图:

class UserRegisterAPIView(APIView):
    serializer_class = UserRegisterSerializer
    permission_classes = [permissions.AllowAny]

    def post(self, request, format=None, *args, **kwargs):
        print(request.data)
        serializer = UserRegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        user_data = serializer.validated_data
        return Response(user_data)

注册序列化器: 我使用了django的默认模型User

from django.contrib.auth.models import User
class UserRegisterSerializer(serializers.ModelSerializer):
    password2   = serializers.CharField(
        style={'input_type': 'password'})

    class Meta:
        model = User
        fields = ["username", "email", "password", "password2"]
        extra_kwargs = {
        'password': {'write_only': True},
        'password2': {'write_only': True}
        }

    def validate(self, data):
        password    = data.get('password')
        password2   = data.pop('password2')

        if len(str(password)) < 5:
            raise serializers.ValidationError("Password is too short.")
        if password != password2:
            raise serializers.ValidationError("Passwords don't match.")
        return data

    def create(self, validated_data):
        username = validated_data.get('username')
        email    = validated_data.get('email')
        password = validated_data.get('password')

        user = User.objects.create_user(username=username, email=email,
                password=password)

        if user and user.is_active:
            return user

注册组件: 我已导入操作注册

注意:我删除了其他输入字段以减少代码

export class Register extends Component {

  state = {
    username: '',
    password: '',
    password2: '',
    email: '',
  }

  onChange = (e) => this.setState({ [e.target.name]: e.target.value })

  onSubmit = (e) => {
    e.preventDefault();
    this.props.register(this.state)
  }

  render() {
    return (
      <div className="col-md-6 m-auto">
        <div className="card card-body mt-5">
          <form onSubmit={this.onSubmit}>
            <div className="form-group">
              <label>Username</label>
              <input
                type="text"
                className="form-control"
                name="username"
                onChange={this.onChange}
              />
            </div>
            <div className="form-group">
              <button type="submit" className="btn btn-primary">
                Register
              </button>
            </div>
            <p>
              Already have an account? <Link to="/login">Login</Link>
            </p>
          </form>
        </div>
      </div>
    )
  }
}


export default connect(null, { register })(Register);

操作:

export const register = ({
  username,
  password,
  password2,
  email
}) => dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json',
    }
  }
  const body = JSON.stringify({
    username,
    password,
    password2,
    email
  });

  axios.post('/user/register/', body, config)
    .then(res => {
      dispatch({
        type: REGISTER_SUCCESS,
        payload: res.data
      })
    }).catch(err => {
      dispatch({
        type: REGISTER_FAIL,
        payload: err
      })
      console.log(err)
    })
}

减速器:

import { REGISTER_SUCCESS, REGISTER_FAIL } from './../actions/types';

const initialState = {
  user: null,
  error: null,
}

export default function (state = initialState, action) {
  switch (action.type) {
    case REGISTER_SUCCESS:
      console.log("Register success")
      return {
        ...state,
        user: action.payload,
      }
    case REGISTER_FAIL:
      return {
        ...state,
        user: null,
        error: action.payload
      }
    default: {
      return state;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

似乎您没有在标头中传递CSRF:

尝试将其放在标题中

'X-CSRFToken': csrftoken

您可以从cookie获得的CSRF令牌值。 有关CSRF的更多信息,请参考Django官方docs