I hope you are well.
I’m developing a web application by NodeJs and ReactJs. When I try to Login by formik with using axios, passportjs cannot redirect me to successLink even if my info are correct.
Gives me 404 not found.
When I don’t use formik and use regular html form passportjs works but this time I can’t use request.isAuthenticated() and I cannot manage users in react.
isAuthenticated() always gives me false in react “localhost:5001” but when I use nodejs “localhost:5000” it gives me true.
Thank you for your answers. Have a great day.
Node.js Backend
commonController.js
const login = async (req, res, next) => {
// form request
// let data = await req.body
// axios request
let data = await JSON.parse(Object.keys(req.body)[0])
const _responsible = await Responsible.findOne({ email: data.email });
console.log(_responsible)
if (!_responsible) {
passport.authenticate('local', {
successRedirect: `${process.env.LOGIN_SUCCESS_URL}`,
failureRedirect: `${process.env.LOGIN_FAIL_URL}1`,
})(req, res, next)
}
else {
if (_responsible && _responsible.isActive == true) {
passport.authenticate('local', {
successRedirect: `${process.env.LOGIN_SUCCESS_URL}`,
failureRedirect: `${process.env.LOGIN_FAIL_URL}1`,
})(req, res, next)
}
else if(_responsible && _responsible.isActive == false){
passport.authenticate('local', {
successRedirect: `${process.env.LOGIN_FAIL_URL}2`,
})(req, res, next)
}
}
}
React
Login.js
{error && error == 1 ?
<p style={{ color: "red" }}>{strings.loginError}</p> : null
}
{error && error == 2 ?
<p style={{ color: "orange" }}>{strings.loginAuthorizationError}</p> : null
}
{/* FORMIK FORM */}
<Formik initialValues={{ email: "", password: "" }}
validationSchema={loginValidationSchema}
onSubmit={async (values) => {
axios.post(`${process.env.REACT_APP_SERVER_URL}/login`, JSON.stringify(values))
.then(response => console.log(response.data))
.catch(err => console.log(err.message))
values.email = "";
values.password = "";
}}
>
{({ errors, touched }) => (
<Form className='loginForm'>
<Field className="loginFormField" name="email" type="email" placeholder={strings.formEmail} />
{errors.email && touched.email ? (
<div className='formErrorMessage'>{errors.email}</div>
) : null}
<Field className="loginFormField" name="password" type="password" placeholder={strings.formPassword} />
{errors.password && touched.password ? (
<span className='formErrorMessage'>{errors.password}</span>
) : null}
<button type="submit">{strings.submitForm}</button>
</Form>
)}
</Formik>