奇怪的POST请求发布csrf_token作为密码

时间:2019-01-31 00:00:44

标签: django reactjs post django-rest-framework

我有一个用于注册用户的Django API视图。从我的客户端ReactJS代码中,我传入了CSRF令牌,但是当我调用它时,我得到了:

[30/Jan/2019 23:45:04] "OPTIONS /newuser/ HTTP/1.1" 200 108

而不是成功的POST调用。这是Django代码:

path('newuser/', views.SignUp.as_view()),

API视图:

class SignUp(APIView):

parser_classes = (JSONParser,)
permission_classes = (AllowAny,)

def post(self, request, format = None):

    username = request.data['username']
    password = request.data['password']

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

    login(request, user)
    returnData = UserSerializer(user)
    return Response(returnData.data)

这是客户端。

loginSubmit() {

    var csrftoken = document.getElementById('token').getAttribute('value');
    console.log(csrftoken);
    fetch('http://localhost:8000/newuser/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password,
      }),
    })

  }

这是我的React POST表单代码,以防万一:

const LoginScreen = (props) => {

  return (
    <div>
      <form onSubmit={props.loginSubmit}>
        <CSRFToken />
        <label className="loginLabel">
          <h3>Username</h3>
          <input name="username" style={{position: 'relative', height: '50%', top: '50%'}} type="text" value={props.value} onChange={props.handleChangeUserName} />
        </label>
        <label className="loginLabel">
          <h3>Password</h3>
          <input name="password" type="text" value={props.value} onChange={props.handleChangePassword} />
        </label>
        <button type="submit" id="loginButton" className="loginButton"><Link to="/app">Login</Link></button>
      </form>
    </div>
  );

}

0 个答案:

没有答案