React Login form throws error "Cannot set headers after they are sent to the client" - sql

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);
}
}
});
});

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();
The response ends response.send("Please enter email and Password!");response.end();, thus the handler once resolved gives that error.

Related

{message: "Auth failed", success: false} message : "Auth failed" success : false

I'm following a Udemy MERN stack course and I am quite a beginner ,I've got stuck in middle of a problem. There is no point in completing it before solving this problem. The problem is with the concept of authorization and concept of protected roles, so when the user is logged in to the interface we have to check whether is user is authorized or not. I followed the instructer end to end exactly according to the instruction and his code.
Using jsonwebtoken, verifiationn is conducted on the basis of encrypted token. whos key is stored in .env file
The output of the network dev tool in the browser :
enter image description here
I have no idea what causes this.
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const dbConfig = require("./config/dbConfig.js");
app.use(express.json());
const userRoute = require("./routes/userRoute");
app.use("/api/user", userRoute);
const port = process.env.PORT || 5000;
console.log(process.env.MONGO_URL);
app.listen(port, () => console.log(`Node server started at port ${port}`));
.env
MONGO_URL = 'mongodb+srv://users:root#cluster0.vnoq4f8.mongodb.net/ngodatabase';
JWT_SECRET = 'ngo_project';
Home.js
import React, { useEffect } from "react";
import axios from "axios";
function Home() {
const getData = async () => {
try {
const response = await axios.post(
"/api/user/get-user-info-by-id",
{},
{
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
}, // headers
}
);
console.log(response.data);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getData();
}, []);
return <div>Home</div>;
}
export default Home;
authmiddleware.js
const jwt = require("jsonwebtoken");
module.exports = async (req, res, next) => {
try {
const token = req.headers["authorization"].split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({
message: "Auth failed",
success: false,
});
} else {
req.body.userId = decoded.id;
next();
}
});
} catch (error) {
return res.status(401).send({
message: "Auth failed",
success: false,
});
}
};
userRoute.js
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const authmiddleware = require("../middlewares/authmiddleware");
router.post("/register", async (req, res) => {
try {
const userExist = await User.findOne({ email: req.body.email });
if (userExist) {
return res
.status(200)
.send({ message: "User already exists", success: false });
}
const password = req.body.password;
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
req.body.password = hashedPassword;
const newuser = new User(req.body);
await newuser.save();
res
.status(200)
.send({ message: "User created successfully", success: true });
} catch (error) {
console.log(error);
res
.status(500)
.send({ message: "Error creating user", success: false, error });
}
});
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res
.status(200)
.send({ message: "User does not exist", success: false });
}
const isMatch = await bcrypt.compare(req.body.password, user.password);
if (!isMatch) {
return res
.status(200)
.send({ message: "Password is incorrect", success: false });
} else {
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
res
.status(200)
.send({ message: "login successful", success: true, data: token });
}
} catch (error) {
console.log(error);
res
.status(500)
.send({ message: "Error logging in", success: false, error });
}
});
router.post("/get-user-info-by-id", authmiddleware, async (req, res) => {
try {
const user = await User.findOne({ _id: req.body.userId });
if (!user) {
return res
.status(200)
.send({ message: "User does not exist", success: false });
} else {
res.status(200).send({
success: true,
data: {
name: user.name,
email: user.email,
},
});
}
} catch (error) {
res.status(500).send({
message: "Error getting user information",
success: false,
error,
});
}
});
module.exports = router;
package.json
jsonwebtoken in package
Login.js
import { Button, Form, Input } from "antd";
import React from "react";
import toast from "react-hot-toast";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
function Login() {
const navigate = useNavigate();
const onFinish = async (values) => {
try {
const response = await axios.post("/api/user/login", values);
if (response.data.success) {
toast.success(response.data.message);
toast("Redirecting to home page");
localStorage.setItem("token", response.data.data);
navigate("/");
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.error("Something went wrong");
}
};
return (
<div className="authentication">
<div className="authentication-form card p-4">
<h1 className="card-title">Welcome Back</h1>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item label="Email" name="email">
<Input placeholder="Email"></Input>
</Form.Item>
<Form.Item label="Password" name="password">
<Input placeholder="Password" type="password"></Input>
</Form.Item>
<Button className="primary-button my-2" htmlType="submit">
LOGIN
</Button>
<Link to="/register" className="anchor mt-2">
CLICK HERE TO REGISTER
</Link>
</Form>
</div>
</div>
);
}
export default Login;
Register.js
import { Button, Form, Input } from "antd";
import React from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
import toast from "react-hot-toast";
function Register() {
const navigate = useNavigate();
const onFinish = async (values) => {
try {
const response = await axios.post("/api/user/register", values);
if (response.data.success) {
toast.success(response.data.message);
toast("Redirecting to login page");
navigate("/login");
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.error("Something went wrong");
}
};
return (
<div className="authentication">
<div className="authentication-form card p-4">
<h1 className="card-title">Nice to meet you</h1>
<Form layout="vertical" onFinish={onFinish}>
<Form.Item label="Name" name="name">
<Input type="text" placeholder="Name" name="name"></Input>
</Form.Item>
<Form.Item label="Email" name="email">
<Input type="email" placeholder="Email" name="email"></Input>
</Form.Item>
<Form.Item label="Password" name="password">
<Input
placeholder="Password"
name="password"
type="password"
></Input>
</Form.Item>
<Button
className="primary-button my-2"
htmlType="submit"
name="submit"
>
REGISTER
</Button>
<Link to="/Login" className="anchor mt-2">
CLICK HERE TO LOGIN
</Link>
</Form>
</div>
</div>
);
}
export default Register;
did you check if you already have the token in your storage ?
check using inspectElement, or try to print the token in authmiddleware.js
like:
const jwt = require("jsonwebtoken");
module.exports = async (req, res, next) => {
try {
const token = req.headers["authorization"].split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
console.log(token); //this line will print the token that given in your request
return res.status(401).send({
message: "Auth failed",
success: false,
});
} else {
req.body.userId = decoded.id;
next();
}
});
} catch (error) {
return res.status(401).send({
message: "Auth failed",
success: false,
});
}
};

Cant´t get cookie - Express

I created a server with express and have some get/post routes.
In the login page, I have a page that shows the form to login:
app.get("/login", (req, res) => {
res.send(`<h1>Iniciar sesión</h1>
<form method='post' action='/login'>
<input type='email' name='email' placeholder='Email' required />
<input type='password' name='password' placeholder='Contraseña' required />
<input type='submit' value='Ingresar' />
</form>
<a href='/register'>Registrarse</a`);
});
Then I have a Post method in which I set the cookies:
app.post("/login", (req, res) => {
const { email, password } = req.body;
const user = users.filter(
(e) => e.email === email && e.password === password
);
if (user.length >= 1) {
res.cookie("userId", user.id);
res.cookie("password", user.password);
res.redirect("/home");
} else {
console.log("contraseña incorrecta");
res.redirect("/login");
}
});
The problem is that when I go to this route, the user.name and user.email are undefined. In other words, I can´t acces to the cookie:
app.get("/home", (req, res) => {
const id = req.cookies.userId;
console.log(id); //this is undefined
const user = users.filter((u) => u.id === id);
//console.log(user);
res.send(`
<h1>Bienvenido ${user.name}</h1>
<h4>${user.email}</h4>
<a href='/'>Inicio</a>
`);
});
Advices?
Here is the complete code:
const express = require("express");
const morgan = require("morgan");
const cookieparser = require("cookie-parser");
const bodyparser = require("body-parser");
const app = express();
const users = [
{ id: 1, name: "Franco", email: "Franco#mail.com", password: "1234" },
{ id: 2, name: "Toni", email: "Toni#mail.com", password: "1234" },
];
app.use(morgan("dev"));
app.use(cookieparser());
app.use(bodyparser.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log(req.cookies);
next();
});
app.get("/", (req, res) => {
res.send(`
<h1>Bienvenidos a Henry!</h1>
${
req.cookies.userId
? `<a href='/home'>Perfil</a>
<form method='post' action='/logout'>
<button>Salir</button>
</form>
`
: `
<a href='/login'>Ingresar</a>
<a href='/register'>Registrarse</a>`
}
`);
});
app.get("/register", (req, res) => {
res.send(`<h1>Registrarse</h1>
<form method='post' action='/register'>
<input name='name' placeholder='Nombre' required />
<input type='email' name='email' placeholder='Email' required />
<input type='password' name='password' placeholder='Contraseña' required />
<input type='submit' value='Registrarse' />
</form>
<a href='/login'>Iniciar sesión</a>`);
});
app.get("/login", (req, res) => {
res.send(`<h1>Iniciar sesión</h1>
<form method='post' action='/login'>
<input type='email' name='email' placeholder='Email' required />
<input type='password' name='password' placeholder='Contraseña' required />
<input type='submit' value='Ingresar' />
</form>
<a href='/register'>Registrarse</a`);
});
app.post("/login", (req, res) => {
const { email, password } = req.body;
const user = users.filter(
(e) => e.email === email && e.password === password
);
if (user.length >= 1) {
res.cookie("userId", user.id);
res.cookie("password", user.password);
res.redirect("/home");
} else {
console.log("contraseña incorrecta");
res.redirect("/login");
}
});
app.get("/home", (req, res) => {
const id = req.cookies;
console.log(id);
const user = users.filter((u) => u.id === id);
//console.log(user);
res.send(`
<h1>Bienvenido ${user.name}</h1>
<h4>${user.email}</h4>
<a href='/'>Inicio</a>
`);
});
app.listen(3000, (err) => {
if (err) {
console.log(err);
} else {
console.log("Listening on localhost:3000");
}
});
Part of your problem is that this code:
const user = users.filter(
(e) => e.email === email && e.password === password
);
produces an Array. So, user is an array.
Therefore when you do this:
res.cookie("userId", user.id);
res.cookie("password", user.password);
Both user.id and user.password are ignoring the match you got in user[0] and are referring to non-existent properties on the user array object. They will end up undefined and thus why res.cookie() is not setting a meaningful value.
You should, instead be doing this:
res.cookie("userId", user[0].id);
res.cookie("password", user[0].password);
But, please don't put a password in a user's cookie. There should be no reason to ever do that. Even more so when it's in plain text. If you want to know if the previous user is logged in or not, then use a cryptographically secure token in the cookie (like something express-session uses). Don't put their password in a cookie.

Express/mssql login form throws "ReferenceError:"" is not defined"

I am creating a basic full stack login form but cannot for the life of my get this connected up properly.I have made a register with no issues. However when coming to the login it is killing me inside.
All I want to do is simply get the user to login from the front end (login class) which is then passed to my server.js and throw the query at the database to return whether the credentials exist (email and password ) and if they do to just simply redirect you to the home page if not a basic error .
This is the route from 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);
}
}
});
});
This is my 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("/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>
);
}
}
Throughout the code I tried to implement as much logging as possible so that I could understand what everything was declared as (the ///// parts are me simply me trying to output the results from recordset which I hoped would be the result of the query ) The bottom line is the error itself.
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
I am no longer receiving Reference error.
Updated 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);
}
}
});
});
Now record set is correctly logged to console however the if statement never seems to work it will always print out "stuck in the else" This message was created by me but i honestly have no idea why even inputting the correct detail in will still make it go to the else.
I have tried multiple if statements as well as the one I have.
The main one I want
if (recordset.length > 0)
The ones I have tried also
if (recorset.email === Email)
if (recorset.email = Email)
if (recorset.email === Password)
if (recorset.email = Password)
Any help would be much appreciated this is the second day stuck on this issue :(
The reason you always hit stuck in the else is because it is outside of the if else block.
I think you are using this mssql package.
Checking this package docs, I wrote a simpler and cleaner version of your code with come corrections.
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");
}
});
You might try this code, I believe this should login successfully. I've also modified to connect to the database only once, rather than on each login attempt.
// Modify as appropriate..
const config = {
user: 'some_user',
password: 'some_password',
server: 'some_server',
database: 'some_db'
};
const dbConnectionPromise = sql.connect(config).then(pool => {
console.log("Database connected successfully");
return pool
}).catch(err => {
console.error("Database connection failed:", err);
});
app.post("/login", async function(req, response) {
console.log("/login");
await dbConnectionPromise;
var request = new sql.Request();
var Email = req.body.email;
var Password = req.body.password;
request.input("email", sql.VarChar, Email);
request.input("password", sql.VarChar, Password);
var queryString = "SELECT * FROM TestLogin WHERE email = #Email AND password = #Password";
request.query(queryString, function(err, queryResult) {
if (err) {
response.status(500).send(err);
} else if (queryResult.recordset.length <= 0) {
response.status(400).send("Incorrect email and/or Password!");
} else if (queryResult.recordset[0].Email.length > 0) {
console.info("/login: login successful..");
req.session.loggedin = true;
req.session.email = Email;
response.redirect("/home");
}
});
});
console.log(`Express listening on port: ${port}`);
app.listen(port);

React adding new users to SQL database (undefined entries)

I have been making a website in which I am beginning to create a registration process.I have created the registration form and a server.js file using npm express. However this keeps throwing this error and I'm not sure why.
This is the error
TypeError: Cannot destructure property 'email' of 'req.body' as it is undefined.
All I want to do is so that when submit button is clicked it the users are simply added to the database.
This is the server.js (The error occurs within this file from what I can gather)
const express = require("express");
const sql = require("mssql");
const app = express();
const port = process.env.PORT || 5000;
app.listen(port, () => `Server running on port ${port}`);
const config = {
user: "sas",
password: "Mypassword456",
server: "DEVSQL_2014", // You can use 'localhost\\instance' to connect to named instance
database: "TestDBWebsite"
};
app.post("/admin-Add-Users", function(req, res) {
res.set("Access-Control-Allow-Origin", "*");
const { email, password } = req.body;
let connection = new sql.ConnectionPool(config, function(err) {
let request = new sql.Request(connection);
request.query(
"insert into Login (email, password) values ('" +
password +
"', '" +
email +
"')"
);
});
res.send({ message: "Success" });
});
register.js
import React from "react";
import "../bootstrap.min.css";
import logo from "../codestone logo.png";
import { Link } from "react-router-dom";
import Popup from "reactjs-popup";
import { Formik } from "formik";
import * as Yup from "yup";
function Register() {
return (
<div className="App">
<Header />
<DisplayUsersCS />
</div>
);
}
class DisplayUsersCS extends React.Component {
constructor() {
super();
this.state = { users: [] };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var self = this;
// On submit of the form, send a POST request with the data to the server.
fetch("/admin-Add-Users", {
method: "POST",
body: {
email: self.refs.email,
password: self.refs.password
}
})
.then(function(response) {
return response.json();
})
.then(function(body) {
console.log(body);
});
}
render() {
console.log(this.state.users);
return (
<div>
<LoginForm></LoginForm>
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="email" ref="email" />
<input type="text" placeholder="password" ref="password" />
<input type="submit" />
</form>
</div>
);
}
}
const LoginForm = () => (
<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(/(?=.*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."),
passwordConfirm: 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">
<label htmlFor="email">Email</label>
<input
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onChange={handleChange}
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"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={errors.password && touched.password && "error"}
/>
{errors.password && touched.password && (
<div className="input-feedback">{errors.password}</div>
)}
<label htmlFor="email">Password Confirmation</label>
<input
name="passwordConfirm"
type="passwordConfirm"
placeholder="Confirm Password"
value={values.passwordConfirm}
onChange={handleChange}
onBlur={handleBlur}
className={
errors.passwordConfirm && touched.passwordConfirm && "error"
}
/>
{errors.passwordConfirm && touched.passwordConfirm && (
<div className="input-feedback">{errors.passwordConfirm}</div>
)}
<button type="submit" action="auth">
Sign Up
</button>
<p>
<Link to="/Login"> Login </Link>
</p>
<p>
<Link to="/reset"> Reset Password </Link>
</p>
</div>
</form>
);
}}
</Formik>
);
function Header() {
return (
<div class="jumbotron">
<img
className="profile-image"
alt="icon"
src={logo}
width="450"
height="80"
/>
</div>
);
}
export default Register;
On client side (react)
To use fetch to post json data, you need to stringify the data in the body
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
On server side (express.js)
You need to include include middleware in order to read the request body. You can refer to the sample codes here https://github.com/expressjs/body-parser

Displaying a specific data in html ionic

I'm trying to display a specific username using the user uid in firebase, but i can't display it in the html. I try to get the username from the userColl by the Uid. For the html, i tried using *ngFor, but there's problem indicating that it can only be used for array
Here's is the code:
read_Username() {
return this.firestore.collection('userColl',ref => ref
.where('userUid', '==', this.userUid)).snapshotChanges();
//return this.firestore.collection('/userColl/userUid' + this.userUid).snapshotChanges();
}
ngOnInit() {
this.user = firebase.auth().currentUser;
//this.userUid = firebase.auth().currentUser.uid
this.read_Username().subscribe(data => {
this.user = data.map(e => {
if(this.user != null){
return {
id: e.payload.doc.id,
userUid: e.payload.doc.data()['userUid'],
username: e.payload.doc.data()['username'],
};
}
})
console.log(this.user);
});
}
The html:
<ion-card class="welcome-card">
<img src="/assets/shapes.svg" alt=""/>
<div>
<ion-card-header >
<ion-card-subtitle></ion-card-subtitle>
<ion-card-title> {{userUid}}</ion-card-title>
</ion-card-header>
<ion-card-content>
<p>{{username?.username}}</p>
</ion-card-content>
Try changing your codes to this:
read_Username() {
return this.firestore.collection('userColl',ref => ref
.where('userUid', '==', this.userUid)).snapshotChanges();
//return this.firestore.collection('/userColl/userUid' + this.userUid).snapshotChanges();
}
userUid:string;
username:string;
ngOnInit() {
this.user = firebase.auth().currentUser;
//this.userUid = firebase.auth().currentUser.uid
this.read_Username().subscribe(data => {
this.user = data.map(e => {
if(this.user != null){
return {
id: e.payload.doc.id,
userUid: e.payload.doc.data().userUid,
username: e.payload.doc.data().username,
};
}
})
console.log(this.user);
});
}
The html:
<ion-card class="welcome-card">
<img src="/assets/shapes.svg" alt=""/>
<div>
<ion-card-header >
<ion-card-subtitle></ion-card-subtitle>
<ion-card-title>{{userUid}}</ion-card-title>
</ion-card-header>
<ion-card-content>
<p>{{username}}</p>
</ion-card-content>
If it doesn't work, change the
userUid: e.payload.doc.data().userUid,
username: e.payload.doc.data().username,
to:
userUid: e.payload.doc.data()['userUid'],
username: e.payload.doc.data()['username'],