Привет! Я разработал свой собственный логин с полным стеком.
Я создал класс для хранения пользователей, и теперь я создаю класс для входа в систему из этих сохраненных пользователей.
Я создал базовую c форму входа с извлечением на мой сервер. js файл.
Однако, кажется, ничего не происходит, когда я пытаюсь войти в систему с помощью этой формы.
Я чувствую, что логика c, стоящая за ним, имеет смысл, но я не могу понять, почему это, похоже, не работает.
Это мой класс Добавить пользователей
class AddUsers extends React.Component {
constructor() {
super();
this.state = { users: [], email: "", password: "", passwordConfirm: "" };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.state.email.length < 8 || this.state.password.length < 8) {
alert(`please enter the form correctly `);
} else {
const data = { email: this.state.email, password: this.state.password };
fetch("/login-user", {
method: "POST", // or 'PUT'
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.error("Error:", error);
});
alert(`Congradulations you have signed up`);
}
}
catch(e) {
console.log(e);
}
render() {
console.log(this.state.users);
return (
<div>
<Formik
class="form-signin"
action="auth"
method="POST"
initialValues={{ email: "", password: "", passwordConfirm: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log("Logging in", values);
setSubmitting(false);
}, 500);
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required")
.matches(
/(?=.*outlook)/,
"This is not a outlook email address."
),
password: Yup.string()
.required("No password provided.")
.min(8, "Password is too short - should be 8 chars minimum.")
.matches(/(?=.*[0-9])/, "Password must contain a number.")
})}
>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<form
onSubmit={handleSubmit}
class="form-signin"
action="auth"
method="POST"
>
<div className="jumbotron">
<h2>Sign Up </h2>
<div className="help">
<Popup trigger={<Link> Help?</Link>} className="center">
<div>
Enter Codestone Email address and Password connected to
the account.
</div>
</Popup>
</div>
<label htmlFor="email">Email</label>
<input
name="email"
type="email"
placeholder="Enter your email"
value1={values.email}
value={this.state.email}
onInput={handleChange}
onChange={e => this.setState({ email: e.target.value })}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}
<label htmlFor="email">Password</label>
<input
name="password"
type="password"
placeholder="Enter your password"
value2={values.password}
value={this.state.password}
onInput={handleChange}
onChange={e => this.setState({ password: e.target.value })}
onBlur={handleBlur}
className={errors.password && touched.password && "error"}
/>
{errors.password && touched.password && (
<div className="input-feedback">{errors.password} </div>
)}
<button class="button" type="submit" onClick={this.onSubmit}>
Sign Up
</button>
<p>
<Link to="/login"> Login Page </Link>
</p>
<p>
<Link to="/reset"> Reset Password </Link>
</p>
</div>
</form>
);
}}
</Formik>
</div>
);
}
}
Это мой сервер. js route
Ошибка согласно chrome - это первая строка
app.post("/login-user", function(request, response) {
var req = new sql.Request();
var email = body.email;
var password = body.password;
try {
if (email && password) {
req.query(
"SELECT * FROM TestLogin WHERE email = ? AND password = ?",
[username, password],
function(error, results, fields) {
if (results.length > 0) {
request.session.loggedin = true;
request.session.username = username;
response.redirect("/home");
} else {
response.send("Incorrect Username and/or Password!");
}
response.end();
}
);
} else {
response.send("Please enter Username and Password!");
response.end();
}
} catch (e) {
console.log(e);
response.status(400);
response.send(e);
}
});
добавлено chrome ошибка
LoginPage.js:42 POST http://localhost:3000/login-user 500 (Internal Server Error)
handleSubmit @ LoginPage.js:42
callCallback @ react-dom.development.js:336
invokeGuardedCallbackDev @ react-dom.development.js:385
invokeGuardedCallback @ react-dom.development.js:440
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:454
executeDispatch @ react-dom.development.js:584
executeDispatchesInOrder @ react-dom.development.js:609
executeDispatchesAndRelease @ react-dom.development.js:713
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:722
forEachAccumulated @ react-dom.development.js:694
runEventsInBatch @ react-dom.development.js:739
runExtractedPluginEventsInBatch @ react-dom.development.js:880
handleTopLevel @ react-dom.development.js:5803
batchedEventUpdates$1 @ react-dom.development.js:24401
batchedEventUpdates @ react-dom.development.js:1415
dispatchEventForPluginEventSystem @ react-dom.development.js:5894
attemptToDispatchEvent @ react-dom.development.js:6010
dispatchEvent @ react-dom.development.js:5914
unstable_runWithPriority @ scheduler.development.js:697
runWithPriority$2 @ react-dom.development.js:12149
discreteUpdates$1 @ react-dom.development.js:24417
discreteUpdates @ react-dom.development.js:1438
dispatchDiscreteEvent @ react-dom.development.js:5881
Я проверил оператор sql в chrome и, похоже, работает при жестком кодировании значения в