Hi I am making a full stack login form. The error I am receiving is ": Cannot set headers after they are sent to the client" see full log at the bottom.
All i want to do is create a login form that will redirect me to the home page in which I can then start work upon the jwt tokens.
Any idea why this is happening? Any suggestions on how to get this form fully working?
Thanks for all your help :)
app.post("/auth", 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 = body.email;
var password = body.password;
console.log(email, password);
try {
request.input("email", sql.VarChar, email);
request.input("password", sql.VarChar, password);
request.query(
"SELECT * FROM TestLogin WHERE email = 'email' AND password = 'password'",
function(error, results, fields) {
if (results.length > 0) {
req.session.loggedin = true;
req.session.email = email;
response.redirect("/home");
} else {
response.send("Incorrect email and/or Password!");
}
response.end();
}
);
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);
}
}
});
});
Login class
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("/auth", {
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(
/(?=.*codestone)/,
"This is not a Codestone 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>
);
}
}
Error
undefined undefined
[0] _http_outgoing.js:535
[0] throw new ERR_HTTP_HEADERS_SENT('set');
[0] ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0] at ServerResponse.setHeader (_http_outgoing.js:535:11)
[0] at ServerResponse.header (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\express\lib\response.js:170:12)
[0] at C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\server.js:183:26
[0] at C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\mssql\lib\base\request.js:395:9
[0] at Request.userCallback (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\mssql\lib\tedious\request.js:471:15)
[0] at Request.callback (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\request.js:56:14)
[0] at Connection.endOfMessageMarkerReceived (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\connection.js:2402:20)
[0] at Connection.dispatchEvent (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\connection.js:1274:15)
[0] at Parser.<anonymous> (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\connection.js:1067:14) {
[0] code: 'ERR_HTTP_HEADERS_SENT'
Update after suggested changes. This still does not redirect user to the hpome page or even show any signs of logging in in user. No errors are displayed in console or withing chrome dev tools. Please advise if you can
app.post("/auth", 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 = body.email;
var Password = body.password;
//console.log(email, password);
try {
request.input("email", sql.VarChar, Email);
request.input("password", sql.VarChar, Password);
request.query(
"SELECT * FROM TestLogin WHERE email = Email AND password = Password",
function(error, results, fields) {
if (results.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!");
}
}
);
// 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);
}
}
});
});