User.id is undefined - javascript

I'm building a website where users can register, but when registration is complete nothing happens, its supposed to enter the site.
I have tested it with console.log and found out that my user.id is undefined.
this is my register on the server side:
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
console.log(email)
return trx('users')
.returning('*')
.insert({
email: email,
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register ' + err))
}module.exports = {
handleRegister: handleRegister
};
and this is my register on the frontend:
import React from 'react';
class Register extends React.Component {
constructor(props){
super(props);
this.state = {
name: '',
email: '',
password: ''
}
}
onNameChange = (event) => {
this.setState({name: event.target.value})
}
onEmailChange = (event) => {
this.setState({email: event.target.value})
}
onPasswordChange = (event) => {
this.setState({password: event.target.value})
}
onSubmitSignIn = () => {
fetch('http://localhost:3000/register', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
password: this.state.password
})
})
.then(response => response.json())
.then(user => {
console.log(user.id);
if (user.id) {
console.log(user, user.id);
this.props.loadUser(user)
this.props.onRouteChange('home');
}console.log(user.id);
})
}
It is on the frontend I have set the console.log and it never enters the if statement.
How do I fix this?

If you are using mongodb the id field is defined as _id

Related

[object%20Object]/undefined in url

AuthService.js
import axios from 'axios';
const GET_AUTH_API_BASE_URL = "http://localhost:8087/auth";
class AuthService {
login(user){
return axios.post(GET_AUTH_API_BASE_URL+"/login",user);
}
getRole(userName,password){
return axios.get(GET_AUTH_API_BASE_URL+"/role/"+userName+"/"+password);
}
}
export default new AuthService();
LoginComponent.js
class LoginUserComponent extends Component {
constructor(props) {
super(props);
this. State = {
userName: "",
password: "",
};
this.changeHandler = this.changeHandler.bind(this);
this.login = this.login.bind(this);
}
changeHandler(event) {
this.setState({ [event.target.name]: event.target.value });
// console.log(this.state.user.userName);
}
login(event) {
let userDet = {
userName: this.state.userName,
password: this.state.password,
};
console.log(userDet);
AuthService.login(userDet).then(
(res) => {
sessionStorage.setItem("token", res.data);
AuthService.getRole(userDet).then((res) => {
sessionStorage.setItem("role", res.data);
});
if (sessionStorage.getItem("role") === "Admin") {
console.log("Admin");
this.props.navigate("/employees");
}
if (sessionStorage.getItem("role") === "User") {
console.log("User");
this.props.navigate("/add-employee");
}
},
(error) => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
alert(resMessage);
}
);
event.preventDefault();
}
RegisterComponent.js
class RegisterUserComponent extends Component {
constructor(props) {
super(props)
this.state ={
userId:0,
userName:'',
password:'',
role:{
roleId:0,
roleName:''
}
}
this.changeHandler=this.changeHandler.bind(this);
}
changeHandler(event){
this.setState({[event.target.name]:event.target.value});
// console.log(this.state.user.userName);
}
submitData=(event)=>{
console.log(this.state.user);
let userDet={
userId:this.state.userId,
userName:this.state.userName,
password:this.state.password,
role:{
roleId:this.state.roleId,
roleName:this.state.roleName
}
}
console.log(userDet);
// axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.post('http://localhost:8087/auth/users',userDet);
event.preventDefault();
this.props.navigate("/")
}
I can able to register a user with role like admin,user.But when I login the registered user, I am getting a axios error as http://localhost:8087/auth/role/[object%20Object]/undefined. My token is storing in session storage but the role(key, value) is not storing.
I have now added my register component. Kindly rectify
Issue
getRole takes two arguments, userName and password
getRole(userName, password) {
return axios.get(GET_AUTH_API_BASE_URL + "/role/" + userName + "/" + password);
}
but the UI is passing a single object
let userDet = {
userName: this.state.userName,
password: this.state.password,
};
...
AuthService.getRole(userDet)
.then((res) => {
sessionStorage.setItem("role", res.data);
});
userName is an object and password is undefined in the getRole function.
Solution
Pass two args.
const { userName, password } = this.state;
...
AuthService.getRole(userName, password)
.then((res) => {
sessionStorage.setItem("role", res.data);
});

TypeError: Cannot read properties of undefined (reading 'protocol') in React using Axios

So basically as the APP.js renders it is not sending requests to the backend. I am calling the currentUser function inside App.js function. Please help me I am stuck
app.js file
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (user) => {
if (user) {
const getidtoken = await user.getIdTokenResult();
currentUser(getidtoken.token)`enter code here`
.then((res) => {
console.log(res);
dispatch({
type: 'LOGGED_IN_USER',
payload: {
email: res.data.email,
name: res.data.name,
role: res.data.role,
_id: res.data._id,
},
});
})
.catch((err) => {
console.log(err);
});
}
});
currentuser.js Function
export const currentUser = async (authtoken) => {
return await axios.post(
process.env.REACT_APP_API_USER,
{},
{ headers: { authtoken: authtoken } }
);
};
enter image description here

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

firebase - Use updateProfile whenever a user signup

I have a problem with firebase, I want when a user creates a user for the first time, add him to updateProfile, personal details.
This is the code I'm trying to do but the code is not running, it does not work for me.
The part with the currentUser does not work, I do not understand why, I also do not get an error.
signupUser = async () => {
const newUser = {
email: 'test#mail.com',
password: '123456'
};
await signup(newUser);
}
call to signup in nodejs
export const signup = (newUser) => (dispatch) => {
axios
.post('/signup', newUser)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
signup - nodejs
//basically call to this function to signup
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password
};
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then((data) => {
const currentUser = firebase.auth().currentUser;
const name = `${"adding some private information"}`;
currentUser.updateProfile({
displayName: name,
})
.then(() => {
console.log("sign in successfully")
});
return data.user.getIdToken();
})
.then((token) => {
return db.doc(`/users/${newUser.handle}`).set("test");
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
console.error(err);
});
};
The issue looks to be that you aren't return the promise from currentUser.updateProfile, ensuring it successfully completes. Try the following by returning the Promise from that method:
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
};
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then((data) => {
const currentUser = firebase.auth().currentUser;
const name = `${"adding some private information"}`;
return currentUser
.updateProfile({
displayName: name,
})
.then(() => {
console.log("sign in successfully");
return data.user.getIdToken();
});
})
.then((token) => {
return db.doc(`/users/${newUser.handle}`).set("test");
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
// probably send an error back?
// return res.status(500).json({ message: 'error' });
console.error(err);
});
};

firebase - Log in again after the user has registered for the first time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Hi everyone I have such a problem,
After a user signs up for my site, for the first time, I want to log in with the user one more time.
I want that after he registers, connect again.
I tried to do it asynchronously, but it does not always work, sometimes I try to log in before the user is registers, I do not know why it does not work.
I want there to be a login only after registration, to force it.
handleSubmit = async () => {
const newUserData = {
email: 'test#mail.com',
password: '123456',
confirmPassword: '123456',
handle: 'test'
};
await signupUser(newUserData);
await signinChat(newUserData);
}
export const signupUser = (newUserData) => (dispatch) => {
axios
.post('/signup', newUserData)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
//basically call to this function to signup
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle,
};
db.doc(`/users/${newUser.handle}`)
.get()
.then((doc) => {
if (doc.exists) {
return res.status(400).json({ handle: "this handle is already taken" });
} else {
return firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password);
}
})
.then((data) => {
userId = data.user.uid;
return data.user.getIdToken();
})
.then((idToken) => {
token = idToken;
const userCredentials = {
handle: newUser.handle,
email: newUser.email,
};
const userPreferences = {
handle: newUser.handle
};
return db.doc(`/users/${newUser.handle}`).set(userCredentials);
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
console.error(err);
if (err.code === "auth/email-already-in-use") {
return res.status(400).json({ email: "Email is already is use" });
} else {
return res
.status(500)
.json({ general: "Something went wrong, please try again" });
}
});
};
export const signinChat = (user) => {
return async (dispatch) => {
const db = firebase.firestore();
firebase.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then(data => {
console.log(data);
const currentUser = firebase.auth().currentUser;
const name = `${user.handle}`;
currentUser.updateProfile({
displayName: name,
})
.then(() => {
db.collection('users')
.doc(data.user.displayName)
.update({
isOnline: true,
})
.then(() => {
const loggedInUser = {
handle: user.handle,
uid: data.user.uid,
email: user.email
}
localStorage.setItem('user', JSON.stringify(loggedInUser));
console.log('User logged in successfully...!');
})
.catch(error => {
console.log(error);
});
});
})
.catch(error => {
console.log(error);
})
}
}
When I try to connect a second time, sometimes it does not work, for example:
image to show the error:

Categories

Resources