I am doing and app with django and react and I want to add authentication. I do it with jwt. Here is the code.
AuthContext.js
export const AuthProvide = ({children}) => {
const [authToken, setAuthToken] = useState(null)
const [user, setUser] = useState(null)
function loginUser(e) {
e.preventDefault()
console.log(e)
axios.post('http://127.0.0.1:8000/api/token/', {
headers: {
'Content-type': 'application/json'
},
username: e.target.name.value,
password: e.target.password.value
})
}
let contextData = {
user: user,
token: authToken,
loginUser: loginUser,
}
return (
<AuthContext.Provider value={contextData}>
{children}
</AuthContext.Provider>
)
}
Login.js
import AuthContext from "../context/AuthContext";
const Login = () => {
const {loginUser} = useContext(AuthContext)
return (
<>
<Header />
<form onSubmit={loginUser}>
<input type='text' name='username' />
<input type='password' name='password' />
<button onClick={loginUser}>Submit</button>
</form>
</>
)
}
App.js
<BrowserRouter>
<AuthProvide>
<Routes>
<Route element={<PrivateRoute/>}>
<Route path='/' element={<Home/>} />
</Route>
<Route path='/login' element={<Login/>} />
</Routes>
</AuthProvide>
</BrowserRouter>
But when I run the form I get settle.js:19 Uncaught (in promise) zt {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
and AuthContext.js:24 Uncaught TypeError: Cannot read properties of undefined (reading ‘value’) in console. In django I did it from django jwt docs
2
Answers
you are not using the right way to send the data inside your
loginUser
Function. thee.target.username.value
will not give you value ofusername
field input (by the way you have usede.target.name.value
, which will anyway not give the value)loginUser
function inside your Login.js component.username
andpassword
fields’ value in a state by usinguseState
hook of react.In the
AuthContext.js
,useState()
to capture the user input for username and password.In the
Login.js
,