I'm sure there's a sound reason as to why I can't get this to work but I've been staring at the code for a long time and I'm brutally stuck. I'm trying to build out a very basic registration form that should store the data in my PostgreSQL database. I'm using bcrypt to hash out the password, but even without still having issues.
My HTML has the following:
<form action="/register/new" method="post">
<label for="username">Username</label>
<input type="text" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<label for="confirm">Confirm Password</label>
<input type="password" name="confirm">
<button type="submit">Submit</button>
</form>
Then for the code I have:
app.get("/register", function(req,res){
res.render("register");
})
app.post('register', function(req,res){
let newUser = {
username: req.body.username,
passwordHash: bcrypt.hashSynce(req.body.password, 8)
}
models.Users.create(newUser).then(function(){
res.redirect('/login');
})
});
The plan for the registration data to be stored and the user redirected to the login page, login stores them in session, and so on. I thought for a bit that the issue was the action on the form but regardless I'm getting Cannot POST /register/new. I've also played around with doing a findOrCreate and do a comparison but I wanted to start with actually just creating before I make it more complex. The same issue occurs with cannot post.
Any thoughts on what I need to change?
Probably would've worked better if I did a app.post("/register"...
Simple miss of an "/"
try this modified code...
app.post('/register', function(req,res) {
let newUser = {
username: req.body.username,
passwordHash: bcrypt.hashSync(req.body.password, 8)
}
// if it does not connect/save try using models.User instead of models.Users below.
models.Users.create(newUser).then(function(){
res.location('/login');
res.redirect('/login');
})
});
Related
Ok, so first off, this is my first post. I've searched high and low for a solution, but have found none. I have posted this first on Udemy, for the course I've taken, but no one has answered, so I'm reposting it here.
I have been trying very hard to figure out why the new-password page will not display correctly for me. The reset link works fine, and I can even reset the password on my new password page when I am sent there from the email link.
However, no matter what I do, I can't get it to display any styling. It only gives me basic html. The logic works fine, it's just the page that doesn't display correctly.
I know it isn't a path issue to the css folder either. If I simply render as another basic page without any token logic, such as replacing my index page with the new-password page, then it displays normally. I just don't know what I'm missing, or if there was some updates that I need to take into consideration.
I'm hoping someone sees this and can help me out. It's the only thing that doesn't work right, and it's very frustrating.
Just to be a little more clear, if I do something like below, and just replace or create a route, the page shows up correctly. It's the token logic I believe that is breaking the rendering, I just don't know how, since I don't get any errors.
Please let me know what code you may need to see, as I'm not sure what sections would be helpful, there are a lot of moving parts here. I will be happy to post whatever is needed.
exports.getNewPassword = (req, res, next) => {
res.render("auth/new-password", {
path: "/new-password",
pageTitle: "Update Password",
});
};
With the logic built-in and following the email reset link, the below will not render any styling, only the html.
exports.getNewPassword = (req, res) => {
const token = req.params.token;
User.findOne({
resetToken: token,
resetTokenExpiration: { $gt: Date.now() },
})
.then((user) => {
if (!user) {
req.flash(
"error",
"That reset password link has already been used."
);
return res.redirect("/");
}
let message = req.flash("error");
message.length > 0 ? (message = message[0]) : (message = null);
res.render("auth/new-password", {
path: "/new-password",
pageTitle: "New Password",
errorMessage: message,
userId: user._id.toString(),
passwordToken: token,
});
})
.catch((err) => console.log(err));
};
I am using ejs for templating as well. As I said above, if I remove all token logic and just render the page as a normal view, it works fine.
<main>
<% if (errorMessage) { %>
<div class="user-message user-message--error"><%= errorMessage %></div>
<% } %>
<form class="login-form" action="/new-password" method="POST">
<div class="form-control">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<input type="hidden" name="userId" value="<%= userId %>">
<input type="hidden" name="passwordToken" value="<%= passwordToken %>">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button class="btn" type="submit">Update Password</button>
</form>
</main>
Well, in case anyone stumbles across this, the answer was pretty simple, though I'm not sure why in this one instance is was a problem. However, the solution was to add a forward slash in front of my path to the css location for the update password page.
Again, not sure why it needed it, seeing as all my other css and view pages were in the same folder structures and worked fine, but it apparently solved the issue. SMDH.
<link rel="stylesheet" href="/css/login.css" />
I am new to react. Currently I am working on creating a login screen. I have this code:
function login(e) {
fetch('/login')
.then(response => {
if(response === 'fail'){
return(SignIn());
}else{
return(Ide());
}
})
.then((proposals) => {
console.log(proposals);
this.setState({ proposals });
});
}
export default function SignIn() {
const classes = useStyles();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Button
type="submit"
fullWidth
onClick={login}
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</form>
</div>
</Container>
);
And then the login handler
app.get('/login', (req, res, next) => {
const { email, password } = req.body;
console.log(email, password);
//User.find({email: })
});
But when I press the submit button, email and password both console log as undefined. How do I send information using react between the client and the server? Thank you in advance
Whenever you use fetch as a way to send info to an endpoint like '/login' above, the req.body needs to be added as part of the fetch call. To do this, people usually do
fetch('/login', {
body: (whatever you send in the form of one object)
});
The body passed in as the second argument can be then used as req.body in your code that console.logs it.
This is not advised though since GET commands usually do not have bodies passed along as the second argument. Usually POST and PUT commands have the body to make it easy to add and change data. What I recommend is do:
fetch('/login/' + email + '/' + password);
This allows for an email and username object to be a part of your url in for your backend to use. This is one of the ways that people do GET commands without passing in a body. With the new format, you should change the backend to be:
app.get('/login/:email/:password', (req, res) => {
const email = req.params.email;
const password = req.params.password;
console.log(email, password);
With :email and :password in the url, this lets you use req.params and then directly call each identifier as the last value.
Btw if you feel like the fetch call above looks messy with the + commands, you can instead do:
fetch(`/login/${email}/${password}`);
Which are Template Literals that make it easier to read code by adding the values directly into the string. (Note they use the ` key next to the 1 key not ' or ")
Also if you want more info on fetch commands, I advise to start with the MDM Documentation. This website is extremely helpful whenever you need to learn something about JS or other web languages.
I got stuck while uploading updating user avatar on my website. I'm using angular and need to upload image using form and get base64 encoding of this image to pass as a parameter into my backend.
onUploadFinished(event){
const avatar ={
avatar:event.file
}
console.log(avatar)
//validate avatar
if(!this.validateService.validateAvatarUpdate(avatar.avatar)){
this.flashMessage.show('Please, select a new avatar', {cssClass: 'alert-danger', timeout:3000});
return false;
}
this.updateService.updateAvatar(avatar).subscribe(data=>{
console.log()
if(data/*.success*/){ //commented cause response doesnt have property success but still registering user without displaying the flash message
this.flashMessage.show('You successfuly changed your avatar', {cssClass: 'alert-success', timeout:3000});
this.router.navigate(['/profile'])
this.authService.getProfile().subscribe(profile=>{
this.user = profile.user;
},
err=>{
console.log(err);
return false;
});
}else{
this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout:3000});
this.router.navigate(['/profile'])
}
});
}
I was trying to use ng2-image-upload here is html
<h6>Upload new photo...</h6>
<!-- <form (submit)="onUserAvatarSubmit()" enctype="multipart/form-data">
<input type="file" name="avatar" class="text-center center-block well well-sm">
<p></p>
<input class="btn btn-primary" value="Upload" type="submit">
</form> -->
<image-upload name="avatar" [class]="'customClass'"
[headers]="{Authorization: this.authToken}"
[buttonCaption]="'Choose an Image'"
[dropBoxMessage]="'or just drop them here'"
(uploadFinished)="onUploadFinished($event)"
[url]="''">
</image-upload>
Maybe anyone had such experience with uploading images, so give me some tips how to deal with it. Thanks here is a screenshot So you see when displaying this image we can see its base64 but I cant take it.
I have an express server and a login page developed in HTML(with jquery). after login button is hit, jQuery fires a HTTP get request to express server and after user gets verified, user should be redirected to landing page with some data like name, gender, age etc(that is fetched from mongoDB on server itself). When I do res.sendFile or res.redirect, The parameters (name, age, gender) could not be sent on the view which is required there in response.
Jquery:
$("#submit").click(function() {
user = $("#email").val();
pass = $("#password").val();
$.post("https://localhost:443/login", {
user: user,
password: pass
}, function(response) {
if (response) {
alert("login success" + response.userName);
}
});
});
HTML:
<form id="grad">
<h1 style="margin-top: -10px; text-shadow: 1px 1px whitesmoke;">Login</h1>
<h3 style="padding-bottom: 30px;font-size: 22px ">Please enter email ID and password.</h3>
<div class="group">
<input type="email" id="email" name="email"><span class="highlight"></span><span class="bar"></span>
<label>Email ID</label>
</div>
<div class="group">
<input type="password" id="password" name="password"><span class="highlight"></span><span class="bar"></span>
<label>Password</label>
</div>
<div class="group">
<input type="submit" id="submit" class="button buttonRed" value="Login" onclick="validateUser()" />
<input type="reset" class="button buttonRed" value="Reset" />
</div>
</form>
Express:
app.post('/login', function (req, res) {
// some logic to validate user and fetch details, which will be used on view.
res.sendFile('landing**strong text**page.html', { root: "public" } );
})
The post route should save the user in session before returning the response to jQuery code. Essentially the response from post route should be only success or response.
There should also be a get route to redirect the user to home page (or the page where u want the user after login).
This get route will first check if there is a user in session then redirect accordingly.
Use express-session to save the session in app.
Simple solution for starter. This is NOT a practical solution in production site, just for starter who wants to learn the basic.
Jquery
$("#submit").click(function() {
user = $("#email").val();
pass = $("#password").val();
$.post("https://localhost:443/login", {
user: user,
password: pass
}, function(response) {
$('body').append(response); //append html to body returned from /login
});
});
Express Server:
app.post('/login', function (req, res) {
// some logic to validate user and fetch details, which will be used on view.
var userInfo = validateAndFetchDetailFunc();
res.send('Username: ' + userInfo.name + '<br>Gender: ' + userInfo.gender);
})
The real solution should be using session to management the login session for user.
User login with username/password
Create a session at the server side, send back a session key or access token to the client.
When the client request user information, use the session key or access token to retrieve the user info
Render the html page with the user info from the saved session
For express server, you can start to learn session with express-session.
I finished this walkthrough for creating a very basic Reddit clone using the MEAN stack. The app included a few different views, such as a view for all posts, a single post, the login form, and the register form, and all of these views were included in a single file: views/index.ejs.
Is putting all the views together like this common practice, or was it merely for brevity in the tutorial? I was hoping to be able to separate at least the login and register forms from the rest of the views in index.ejs for the sake of organization, but placing them in a login.ejs file in views causes a 404.
Login portion of views/index.ejs
<script type="text/ng-template" id="/login.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-show="error" class="alert alert-danger row">
<span>{{ error.message }}</span>
</div>
<form ng-submit="logIn()"style="margin-top:30px;">
<h3>Log In</h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" ng-model="user.username"></input>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" ng-model="user.password"></input>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
</script>
Login portion of routes/index.js
router.post('/login', function(req, res, next){
if(!req.body.username || !req.body.password){
return res.status(400).json({message: 'Please fill out all fields'});
}
passport.authenticate('local', function(err, user, info){
if(err){ return next(err); }
if(user){
return res.json({token: user.generateJWT()});
} else {
return res.status(401).json(info);
}
})(req, res, next);
});
Login portion of controller
.state('login', {
url: '/login',
templateUrl: '/login.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth){
if(auth.isLoggedIn()){
$state.go('home');
}
}]
})
I don't understand how the views fit together in this app. What is telling the app to find the login template in index.ejs, and how can I redirect the app to look in a different file?
The way they did this is a little strange, but it was most likely for the sake of brevity.
The reason why it's 404'ing is because of how the routes are set up. There's a single route to serve index.ejs, and the rest of the routing is handled client-side through Angular. In fact, the only reason they used ejs is because they wanted to send it using Express' res.render() method most likely. (Although, since it's just HTML from what I saw, instead of actually using any EJS, they could likely just as easily used Express' res.sendFile() method, or prior to 4.8.0, res.send() in conjunction with Node's builtin fs.readFile to send the plain HTML file.
If you wanted to split out the views you'd have to set up server-side routes, but I guess they were dead set on a single-page app. More commonly, views that are rendered on the server-side are split out into individual files, with a main "layout", in which other views are included into.