我在我的应用程序中注册新用户时遇到了Bad Reqauest 400
问题。我使用的是Django 4和React 18。
我已经设置了CORS头,并添加了localhost:3000。我还检查了登录,它工作正常。我在注册时遇到了问题。我是React的新手,我不确定代码有什么问题。当我检查comsole时,我得到以下错误:
我的django文件如下:
serializers.py
class UserRegistrationSerializer(serializers.ModelSerializer):
# Confirm password field in our Registration Request
password2 = serializers.CharField(style={'input_type':'password'})
class Meta:
model = User
fields=['email', 'password', 'password2']
extra_kwargs={
'password':{'write_only':True}
}
# Validating Password and Confirm Password while Registration
def validate(self, attrs):
password = attrs.get('password')
password2 = attrs.get('password2')
if password != password2:
raise serializers.ValidationError("Password and Confirm Password doesn't match")
return attrs
def create(self, validate_data):
return User.objects.create_user(**validate_data)
views.py
def get_tokens_for_user(user):
refresh = RefreshToken.for_user(user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
class UserRegistrationView(APIView):
renderer_classes = [UserRenderer]
def post(self, request):
serializer = UserRegistrationSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
token = get_tokens_for_user(user)
return Response({'token':token, 'msg':'Registration Successful'}, status=status.HTTP_201_CREATED)
我React文件如下:
client.js
import config from './config';
import jwtDecode from 'jwt-decode';
import * as moment from 'moment';
const axios = require('axios');
class DjangoAPIClient {
constructor(overrides) {
this.config = {
...config,
...overrides,
};
this.authToken = config.authToken;
this.login = this.login.bind(this);
this.apiClient = this.getApiClient(this.config);
}
/* ----- Client Configuration ----- */
/* Create Axios client instance pointing at the REST api backend */
getApiClient(config) {
const initialConfig = {
baseURL: `${config.apiBasePath}`,
headers: {
"Content-type": "application/json"
}
};
const client = axios.create(initialConfig);
// adding jwt token to headers ({Authorization: Bearer $token}) to authenticate request:
client.interceptors.request.use(localStorageTokenInterceptor);
return client;
}
/* ----- Authentication & User Operations ----- */
/* Authenticate the user with the backend services.
* The same JWT should be valid for both the api and cms */
login(email, password) {
delete this.apiClient.defaults.headers['Authorization'];
const form_data = {
"email": email,
"password": password
}
return this.apiClient
.post('/api/user/', form_data)
.then((resp) => {
localStorage.setItem('token', JSON.stringify(resp.data));
return this.fetchUser();
})
.catch((error) => {
console.log(error)
});
}
// After loggin in the information about user are saved to localStorage
fetchUser() {
return this.apiClient.get('/api/user/profile/')
.then(({data}) => {
localStorage.setItem('user', JSON.stringify(data));
return data;
});
}
register(email, password) {
const registerData = {
"email": email,
"password": password,
"is_active": true,
};
return this.apiClient.post('/api/user/register/', registerData).then(
(resp) => {
console.log(data)
return resp.data;
});
}
// Logging out is just deleting the jwt.
logout() {
// Add here any other data that needs to be deleted from local storage
// on logout
localStorage.removeItem('token');
localStorage.removeItem('user');
}
}
// every request is intercepted and has auth header injected.
function localStorageTokenInterceptor(config) {
const headers = {};
const tokenString = localStorage.getItem('token');
if (tokenString) {
const token = JSON.parse(tokenString)["token"];
const decodedAccessToken = jwtDecode(token.access);
const isAccessTokenValid =
moment.unix(decodedAccessToken.exp).toDate() > new Date();
if (isAccessTokenValid) {
headers['Authorization'] = `Bearer ${token.access}`;
} else {
alert('Your login session has expired');
// console.log("Session expired")
}
}
config['headers'] = headers;
return config;
}
export default DjangoAPIClient;
config.js
import runtimeEnv from '@mars/heroku-js-runtime-env';
// to read env variables
const env = runtimeEnv();
const config = {
apiBasePath: env.REACT_APP_API_BASE_PATH || "http://localhost:8000",
reactAppMode: process.env.REACT_APP_MODE || 'dev',
};
export default config;
register.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import DjangoAPIClient from '../../client';
import config from '../../config';
const client = new DjangoAPIClient(config);
const AddUser = () => {
const [error, setError] = useState({ email: "", password: "" , password2: ""})
const [addUserForm, setAddUserForm] = useState({ email: '', password: '' , password2: ""})
const navigate = useNavigate()
const toLoginPage = () => {
navigate("/login/")
}
const onAddUser = (e) => {
e.preventDefault()
setError(false)
if (addUserForm.email.length <= 0) {
// setLoading(false)
return setError({ email: "Please Enter Email Address" })
}
if (addUserForm.password.length <= 0) {
// setLoading(false)
return setError({ password: "Please Enter Password" })
}
if (addUserForm.password2.length <= 0) {
// setLoading(false)
return setError({ password: "Please Enter Password" })
}
client.register(addUserForm.email, addUserForm.name, addUserForm.password, addUserForm.password2)
.then(() => {
toLoginPage()
})
.catch((err) => {
setError(true);
console.log(err)
});
}
return (
<div className='App'>
<header className="App-header">
<h1>Add new user</h1>
<form className="" onSubmit={(e) => onAddUser(e)}>
<input type="hidden" name="remember" defaultValue="true" />
<div className="">
<div>
<input
type={"text"}
name={"email"}
label={"Email"}
error={error.email}
value={addUserForm.email}
onChange={(e) => setAddUserForm({ ...addUserForm, email: e.target.value })}
className=""
placeholder="Email address"
/>
</div>
<div>
<input
type={"password"}
name={"password"}
label={"Password"}
error={error.password}
value={addUserForm.password}
onChange={(e) => setAddUserForm({ ...addUserForm, password: e.target.value })}
className=""
placeholder="Password"
/>
</div>
<div>
<input
type={"password"}
name={"password2"}
label={"Password2"}
error={error.password2}
value={addUserForm.password2}
onChange={(e) => setAddUserForm({ ...addUserForm, password2: e.target.value })}
className=""
placeholder="Password2"
/>
</div>
</div>
<div>
<button
title={"AddUser"}
error={error.password}
>
Add user
</button>
</div>
</form>
</header>
</div>
)
}
export default AddUser;
1条答案
按热度按时间hjzp0vay1#
您需要两个参数
但你传递了4个参数