sql - Express/mssql 登录表单抛出“ReferenceError:”“未定义”
问题描述
我正在创建一个基本的完整堆栈登录表单,但在我的一生中无法正确连接。我已经注册,没有任何问题。但是,当登录时,它正在杀死我。
我想做的只是让用户从前端(登录类)登录,然后将其传递给我的 server.js 并将查询扔到数据库中以返回凭据是否存在(电子邮件和密码)以及它们是否存在如果不是基本错误,只需将您重定向到主页即可。
这是来自 server.js 的路由
app.post("/login", function(req, response) {
sql.connect(config, function(err) {
if (err) {
console.log(err + "initial connection");
console.log(config.server);
} else {
try {
var request = new sql.Request();
var body = req.body;
console.log(body);
var Email = req.body.email;
var Password = req.body.password;
console.log(
"this is the email" + Email,
"this is the password" + Password
);
try {
request.input("email", sql.VarChar, Email);
request.input("password", sql.VarChar, Password);
var queryString =
"SELECT * FROM TestLogin WHERE email = @Email AND password = @Password";
console.log("this is the query string " + queryString);
request.query(queryString, function(err, recordset) {
if (err) console.log(err);
response.json(recordset);
if (recordsets.Email.length > 0) {
req.session.loggedin = true;
req.session.email = email;
response.redirect("/home");
} else if (results.length < 0) {
response.send("Incorrect email and/or Password!");
console.log(err);
}
});
// response.send("Please enter email and Password!");
// response.end();
} catch (e) {
console.log(e);
response.status(400);
response.send(e);
}
} catch (e) {
console.log(e);
response.status(400);
response.send(e);
}
}
});
});
这是我的登录类
class Login extends React.Component {
constructor() {
super();
this.state = { email: "", password: "" };
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", {
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);
});
}
}
catch(e) {
console.log(e);
}
render() {
console.log(this.state.email);
console.log(this.state.password);
return (
<div>
<Formik
class="form-signin"
action="auth"
method="POST"
initialValues={{ email: "", password: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log("Logging in", values);
setSubmitting(false);
}, 500);
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required")
.matches(
/(?=.*@)/,
"This is not a 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>Login </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}>
Login
</button>
<p>
<Link to="/login"> Login Page </Link>
</p>
<p>
<Link to="/reset"> Reset Password </Link>
</p>
</div>
</form>
);
}}
</Formik>
</div>
);
}
}
在整个代码中,我尝试实现尽可能多的日志记录,以便我可以理解所有声明的内容(///// 部分只是我试图从记录集中输出结果,我希望这将是查询)底线是错误本身。
Server running on port 5000
[0] { email: 'dfhf@.co.uk', password: '1234556789' }
[0] this is the emaildfhf@.co.uk this is the password1234556789
[0] this is the query string SELECT * FROM TestLogin WHERE email = @Email AND password = @Password
[0] ////////////////////undefined
[0] ////////////////////[object Object]
[0] ////////////////////[object Object]
[0] C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\server.js:190
[0] if (recordsets.Email.length > 0) {
[0] ^
[0]
ReferenceError: recordsets is not defined
我不再收到参考错误。更新了 server.js
app.post("/login", function(req, response) {
sql.connect(config, function(err) {
if (err) {
console.log(err + "initial connection");
console.log(config.server);
} else {
try {
var request = new sql.Request();
var body = req.body;
console.log(body);
var Email = req.body.email;
var Password = req.body.password;
console.log(
"this is the email" + Email,
"this is the password" + Password
);
try {
request.input("email", sql.VarChar, Email);
request.input("password", sql.VarChar, Password);
var queryString =
"SELECT * FROM TestLogin WHERE email = @Email AND password = @Password";
console.log("this is the query string " + queryString);
request.query(queryString, function(err, recordset) {
if (err) console.log(err);
response.json(recordset);
console.log(recordset);
if (recordset.email > 0) {
console.log("made it into if stamtnet ");
req.session.loggedin = true;
req.session.email = email;
response.redirect("/home");
} else recordset.length < 0;
//response.send("Incorrect email and/or Password!");
console.log("stuck in the else " + err);
});
// response.send("Please enter email and Password!");
// response.end();
} catch (e) {
console.log(e);
response.status(400);
response.send(e);
}
} catch (e) {
console.log(e);
response.status(400);
response.send(e);
}
}
});
});
现在记录集已正确记录到控制台但是 if 语句似乎永远不会工作它总是会打印出“卡在 else”这条消息是我创建的,但老实说我不知道为什么即使输入正确的细节仍然会成功去别的地方。
我已经尝试了多个 if 语句以及我拥有的一个。我想要的主要的
if (recordset.length > 0)
我也试过的
if (recorset.email === Email)
if (recorset.email = Email)
if (recorset.email === Password)
if (recorset.email = Password)
任何帮助将不胜感激这是在这个问题上停留的第二天:(
解决方案
你总是打的原因stuck in the else
是因为它在 if else 块之外。
我想你正在使用这个mssql包。检查这个包文档,我写了一个更简单、更干净的代码版本,并进行了更正。
app.post("/login", async (req, response) => {
try {
await sql.connect(config);
var request = new sql.Request();
var { Email, Password } = req.body;
console.log({ Email, Password });
request.input("email", sql.VarChar, Email);
request.input("password", sql.VarChar, Password);
var queryString = "SELECT * FROM TestLogin WHERE email = @Email AND password = @Password";
const result = await request.query(queryString);
if (result.recordsets[0].length > 0) {
console.info("/login: login successful..");
response.send("User logined");
} else {
response.status(400).send("Incorrect email and/or Password!");
}
} catch (err) {
console.log("Err: ", err);
response.status(500).send("Check api console.log for the error");
}
});
推荐阅读
- python - 使 tkinter 画布区域更暗
- html - 两个块:一个具有动态宽度,一个与动态一个宽度相同
- html - 如何解决 bootstrap 4 网格系统的问题?
- .htaccess - .htaccess 中的 301 重定向将旧文件路径/名称附加到新 url
- sql - SQL 重叠查询
- python - 如何使用 Pandas 计算两个数据帧之间的百分比差异?
- python - 使用 pandas 将数据添加到 Dataframe
- angular - angular primeng 冻结标题行,上面有标题行
- google-signin - Google 登录 - 检测是否已登录并提示用户
- javascript - Flot JS 将目标变成菱形