MissingPasswordError: No password given - javascript

I can signup users just fine on my website, but when I test it with Postman I get this error:
MissingPasswordError: No password given
I also cannot login because the password/username combination is incorrect, so there's definitely something wrong but I can't for the life of me figure out what.
This is my html input field for the password:
<input type="password" class="input--text" name="password" id="password">
signup.js with my fetch function:
const btnSignup = document.querySelector('.btn').addEventListener('click', function () {
let username = document.querySelector('#username').value;
let password = document.querySelector('#password').value;
let bday = document.querySelector('#bday').value;
fetch('http://localhost:3000/users/signup', {
method: "post",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'username': username,
'password': password,
'bday': bday
})
}).then(response => {
return response.json();
}).then(json => {
if (json.status === 'success') {
let feedback = document.querySelector('.alert');
feedback.textContent = "Sign up successful!";
feedback.classList.remove('hidden');
}
})
})
And this is my signup function in my auth.js controller:
const signup = async (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
const bday = req.body.bday;
const user = new Users({
username: username
});
/*user.bday = bday;*/
await user.setPassword(password);
await user.save()
.then(result => {
console.log(result.id);
let token = jwt.sign({
id: result._id
}, "{this is a secret}");
res.json({
'status': 'success',
'data': {
'token': token
}
})
}).catch(error => {
res.json({
'status': 'error'
})
});
}
I've added bodyParser, made sure the name for my input fields are correct, ...

Solved! Turns out my code was correct, but I forgot to set the raw body in Postman to JSON (default was text).

Related

Login successful with wrong credentials swagger, nodeJS, JWT

Created a login method but it spits out the token regardless of what is entered in the Userfields
This uses swagger API and I'm trying to develop the frontend and backend
I'm relatively new to nodejs/javascript
Any Help would be appreciated!
login.js
var form = document.getElementById('login')
form.addEventListener('submit', login)
async function login(event) {
event.preventDefault()
const username = document.getElementById('username').value
const password = document.getElementById('password').value
const result = await fetch('/v1/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
password
})
}).then((res) => res.json())
if (result.status === 'ok') {
// everythign went fine
console.log('Got the token: ', result.data)
localStorage.setItem('token', result.data)
alert('Login Successful')
return false;
} else {
alert(result.error)
}
}
userController.JS
login: async (req,res)=> {
const { userName, password } = req.body
const existUsername = await userModel.findOne({ userName: req.body.userName, password: req.body.password}).then((existUsername) =>{
if (existUsername){
res.status(400).json({status: 'Failed', message: `User was Not found`, data: null})
return;
}
try{
async() => {
await bcrypt.compare(password, req.body.password) }
// the username, password combination is successful
const token = jwt.sign(
{
id: userModel._id,
userName: userModel.userName
},
JWT_SECRET
)
res.json({ status: 'ok', data: token })
}
catch (e) {
res.status(400).json({status: 'Failed', message: `${e.message}`, data: null})
}
});
},

my put method duplicate the code insteade of updating

i am trying to store user data in mongodb using put method .my intension is to update those data if there exist or create new. but my method create new data insteade of updating..
this code is from client side(here first i uploaded my image to the imgbb then i save it to server).. .
const image = data.image[0];
const formData = new FormData();
formData.append('image',image)
const API_KEY = '4957c3c668ded462db1fb1002c4535e6';
const url = `https://api.imgbb.com/1/upload?key=${API_KEY}`;
fetch(url,{
method : 'POST',
body : formData,
})
.then(res => res.json())
.then(result => {
if(result.success){
console.log('image',result.data.url)
const img = result.data.url;
const dataOfuser = {
user : user?.displayName,
email : user?.email,
phone: data.phone,
city: data.city,
education: data.education,
img: img
}
console.log(dataOfuser)
fetch(`http://localhost:5000/user/:${user.email}`,{
method:"PUT",
headers:{
'Content-Type': 'application/json'
},
body : JSON.stringify(dataOfuser)
})
.then(res => res.json())
.then(data => {
if(data.acknowledged){
toast.success('Profile Updated')
}
})
}
})
};
these are the code from mongodb
app.put('/user/:email',async(req,res)=>{
const email = req.params.email;
const user = req.body;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user,
};
const result = await userCollection . updateOne ( filter , updateDoc , options);
res.send(result);
});
You could try to send email and user as body and
app.put("/user/email", async (req, res) => {
const { dataOfuser } = req.body; //this finds all
const { email, user, phone, city, etc} = dataOfuser; //this extracts the values, but probably better to send each values by themselves
You can also just send user and email etc on their own, instead of as one object:
body: JSON.stringify({ user, email, phone, city, education, img })
You can also try to add curlybraces around dataOfuser in the body: JSON.stringify({ dataOfuser })
const res = await userCollection
.updateOne(
{ email: email} *find the user by his email*
{ $set: {email: email, phone: phone, city: city etc.}}) *set email to email from body*
})
You should also have default value in inputs as their current value, so the fields doesn't get overwritten as null or blank

Getting Request json data in C# in an HttpPost method

Im in the process of converting my nodejs implementation of my backend to c#. I want to get the request body from my client. How do i access the request body in c#. I then want to use the user input from the client to make another api call using the users parameters.
Here is the front end code
class User {
constructor(userData) {
this.user = userData.id;
this.login = userData.login;
this.password = userData.password;
this.email = userData.email;
this.external_user_id = userData.external_user_id;
this.facebook_id = userData.facebook_id;
this.twitter_id = userData.twitter_id;
this.full_name = userData.full_name;
this.phone = userData.phone;
this.website = userData.website;
this.custom_data = userData.custom_data;
this.user_tags = userData.user_tags;
this.avatar = userData.avatar;
this.created_at = userData.created_at;
this.updated_at = userData.updated_at;
this.last_request_at = userData.last_request_at;
//encrypt the password
}
}
export default User;
async signUp(userCredentials) {
let userForm = new User(userCredentials);
fetch("http://localhost:8080/auth/signup", {
method: 'POST',
body: JSON.stringify(userForm),
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (!response.ok) {
throw Error(`Error message: ${response.statusText}`)
}
console.log(response)
return response.json()
})
.then(json => {
console.log(json);
sessionStorage.setItem('session_token', json.session_token)
this.signIn({ login: userForm.login, password: userForm.password });
})
.catch(error => console.log(error))
}
Here is the nodejs implementation
router.post("/signup", async (req, res) => {
let reqBody = req.body;
console.log(reqBody.password);
console.log(req.headers["cb-token"]);
let cbToken = req.headers["cb-token"];
const userObj = {
user: {
login: req.body.login,
password: req.body.password,
email: req.body.email,
full_name: req.body.full_name,
phone: req.body.phone,
website: req.body.website
}
}
console.log(`token in auth route ${res.locals.session_token}`)
fetch("https://api.connectycube.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"CB-Token": res.locals.session_token
},
body: JSON.stringify(userObj)
})
.then(response => {
if (!response.ok) {
throw Error(`Error message: ${response.statusText}`)
}
return response.json()
})
.then(data => {
console.log(data)
const resObj = Object.assign(data, { session_token: res.locals.session_token });
res.status(200).json(resObj);
})
.catch(error => {
console.log(error)
res.status(400).json(error)
})
})

Fetch API response with react and Express.js won't show any result with console.log

I have a login form that sends data to an Express.js backend using fetch. On the client side, when I want to display the results of the fetch call when it completes nothing is displayed (and it never reaches the data callback). I don't seem to be getting any errors, but I know that the data is successfully being sent to the backend.
Here's the Express.js server code:
const express = require('express');
const User = express.Router();
const bcrypt = require('bcrypt');
const user = require('../Models/user');
this is edited
function loginRouteHandler(req, res) {
user.findOne(
{
where: {
userName: req.body.userName,
},
},
)
.then((data) => {
if (bcrypt.compareSync(req.body.password, data.password)) {
req.session.userName = req.body.userName;
req.session.password = req.body.password;
console.log(req.session);
res.status(200).send('Success!');
} else {
res.status(400).send('some text');
}
});
}
User.route('/').get(getRouteHandler);
User.route('/register').post(postRouteHandler);
User.route('/login').post(loginRouteHandler);
module.exports = User;
And here's the fetch call:
fetch('http://localhost:4000/login',{
method: 'POST',
headers: {
'Accept': 'application/json,text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
userName: this.state.userName,
password: this.state.password,
}),
}).then((response)=>{
if(response.ok){
console.log(response)
}
else {
console.log("a problem")
}
}).then((data)=>{
console.log(data)
});
In your loginRouteHandler, if the bcrypt compare succeeds nothing is returned in the response. So in the first branch of the if statement, put res.send('Success!') or something similar.
Here's an example:
function loginRouteHandler(req, res) {
user.findOne(
{
where: {
userName: req.body.userName,
},
},
)
.then((data) => {
if (bcrypt.compareSync(req.body.password, data.password)) {
req.session.userName = req.body.userName;
req.session.password = req.body.password;
console.log(req.session);
res.status(200).send('Success!');
} else {
res.status(400).send('some text');
}
});
}
UPDATE: you're also not getting the output of the fetch response with .text() or .json(). You have to update the fetch call to the following:
fetch(/* stuff */).then((response)=>{
if(response.ok){
console.log(response)
}
else {
console.log("a problem")
}
return response.text()
}).then((data)=>{
console.log(data)
});
Remove ok from response.ok
Remove .then((data)=>{ console.log(data) });
And check console log.
}).then((response)=>{
if(response){
console.log(response)
}
else {
console.log("a problem")
}
}).then((data)=>{
console.log(data)
});

How to do a login verification

I am creating a system in nodejs + mongodb but I am having difficulty checking if the email and password match.
this is the function that sends the parameters to the api:
function log(e){
e.preventDefault();
let email = document.querySelector('input[name="email"]').value;
let password = document.querySelector('input[name="password"]').value;
let loginstatus = document.querySelector('#loginstatus');
fetch('http://localhost:3000/userV', { method: 'post', headers: {Accept: 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify({
email: email,
senha: password
})
}).then((resp) => {
if(resp.status == 200){
}else{
loginstatus.textContent = 'Usuario ou senha incorretos!';
loginstatus.style.color = 'red';
}
}).catch((err) => {
alert("Ouve um erro no servidor.\nErro:"+err);
});}
here is where it should be doing the verification but always returns "yes", what is wrong in my form? would you have another recommended way to do it?
async index(req, res) {
let reqemail = req.params.email;
let reqsenha = req.params.senha;
const users = await Users.find({ email: reqemail });
if(reqsenha == users.senha){
return res.send('yes')
}else{
return res.send('no')
}
}

Categories

Resources