So, I am making a login form and I have already implemented the fetch API
const form = {
email: document.querySelector("#signin-email"),
password: document.querySelector("#signin-password"),
submit: document.querySelector("#signin-btn-submit"),
messages:document.getElementById("form-messages")
};
let button = form.submit.addEventListener("click", (e)=> {
e.preventDefault();
const login = 'https://ffcc-app.herokuapp.com/user/login';
fetch(login, {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => {
console.log(err);
});
});
I am also getting the desired output:
The problem is I have to redirect to the main page when 'login successful' else I have to display a message saying 'user does not exist'. how should I do that? What else should I add to my code?
const form = {
email: document.querySelector("#signin-email"),
password: document.querySelector("#signin-password"),
submit: document.querySelector("#signin-btn-submit"),
messages: document.getElementById("form-messages"),
};
let button = form.submit.addEventListener("click", (e) => {
e.preventDefault();
const login = "https://ffcc-app.herokuapp.com/user/login";
fetch(login, {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
// code here //
if (data.error) {
alert("Error Password or Username"); /*displays error message*/
} else {
window.open(
"target.html"
); /*opens the target page while Id & password matches*/
}
})
.catch((err) => {
console.log(err);
});
});
login sucess and error handled by data.error as mentioned in your screenshot
👉 https://i.stack.imgur.com/WJBh2.png
function signIn(email, password) {
var userObj = {email: email, password: password};
var jsonBody = JSON.stringify(userObj);
fetch(server + "/auth/authorization", {
// mode: "no-cors",
method: 'POST',
headers: {
"Accept-language": "RU",
"Content-Type": "application/json"
},
body: jsonBody
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert("Error Password or Username");
} else {
return data;
}
})
.catch((err) => {
console.log(err);
});
}
Related
Given is an application for managing users. Following help files are used for this purpose:
AuthenticationAction.js
ManagementAction.js
AuthenticationAction.js is used for authentication:
export function authenticateUser(userID, password) {
console.log("Authenticate")
return dispatch => {
dispatch(getAuthenticateUserPendingAction());
login(userID, password).then(userSession => {
const action = getAuthenticationSuccessAction(userSession);
dispatch(action);
}, error => {
dispatch(getAuthenticationErrorAction(error));
}).catch(error => {
dispatch(getAuthenticationErrorAction(error));
})
}
}
function login(userID, password) {
const hash = Buffer.from(`${userID}:${password}`).toString('base64')
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Basic ${hash}`
},
};
return fetch('https://localhost:443/authenticate', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
function handleResponse(response) {
console.log(response)
const authorizationHeader = response.headers.get('Authorization');
return response.text().then(text => {
if (authorizationHeader) {
var token = authorizationHeader.split(" ")[1];
}
if (!response.ok) {
if (response.status === 401) {
logout();
}
const error = response.statusText;
return Promise.reject(error);
} else {
let userSession = {
/* user: data, */
accessToken: token
}
return userSession;
}
});
}
ManagementAction.js is there for the Crud Functions.
export function createUser(userID, username, password) {
console.log("Create a User")
return dispatch => {
dispatch(getShowUserManagementAction());
createaUser(userID, username, password).then(userSession => {
const action = getShowUserManagementActionSuccess(userSession);
dispatch(action);
}, error => { dispatch(getShowUserManagementErrorAction(error)); }).catch(error => { dispatch(getShowUserManagementErrorAction(error)); })
}
}
function createaUser(userID, username, password) {
const token = "whatever"
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ userID: userID, userName: username, password: password })
};
console.log(requestOptions)
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
question:
Now if I want to use the createaUser function instead of the hardcoded token value with the accestoken I created in login, how do I get the accesstoken and how do I have to rewrite the createaUser function ?
you can store the token you created in the local storage like this:
AuthenticationAction.js
let userSession = {
/* user: data, */
accessToken: token
}
localStorage.setItem("token", userSession.accessToken)
and you can access it as below:
ManagementAction.js
function createaUser(userID, username, password) {
const token = localStorage.getItem("token")
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
then
so you can send your token value with the request
Are the async and await in the right places given this arrow function.
What about the const at the start? Is that okay?
Flow of the function as well as it's compartmentalization. (I put it in a different file, and upon submitting a form in my signup component, it will be called)
Should I save the results of this function in a variable in my signup component and then evaluate it there to see what to do next?
Helpful info:
I am doing form validation with Yup prior to submitting the form. So all that is being returned from the server is "email taken" or "successful registration".
Thank you!
/*
File: src/utils/authentication.js
Author: jreyes
Date: 01-26-2021
*/
/** Register new user */
const signupAuth = async () => {
await fetch('http://localhost:8080/signup', {
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
firstname,
lastname
})
})
.then(response => {
if (!response.ok) {
throw new Error('Please check your network.');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
export { signupAuth };
you should try to do something like that:
export const signupAuth = (email, password, firstname, lastname) => {
return fetch('http://localhost:8080/signup', {
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
firstname,
lastname
})
})
};
and after :
import { signupAuth } from "./file";
signupAuth(email, password, firstname, lastname)
.then(response => {
})
.catch(error => {
});
// or this way
try {
const response = await signupAuth(email, password, firstname, lastname);
// do you stuff here
} catch (error) {
// handle error here
}
i set my values in Async storage while logging
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
})
.catch((error) => {
console.log(error);
})
}
and delete those while logging out.
fetch('https://xxxxxx/xxxx/userLogout.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userEmail
})
}).then((response) => response.json())
.then(async (responseJson) => {
try {
const keys = await AsyncStorage.getAllKeys();
await AsyncStorage.multiRemove(keys);
this.props.navigation.toggleDrawer();
this.setState({ isLoading: false })
this.props.navigation.navigate('loginScreen');
} catch (error) {
console.log("Error clearing app data");
}
}).catch((error) => {
console.log(error);
})
but again if i login with new user the old user details is shown in login page. if i reload my app the new values stored in async storage is shown why this is happen and this is not happening?
I am using the AsyncStorage here.
async componentDidMount() {
const userEmail = await AsyncStorage.getItem('userEmail');
const name = await AsyncStorage.getItem('name');
const profilePicture = await AsyncStorage.getItem('profilePicture');
const userID = await AsyncStorage.getItem('userID');
this.getWish();
this.getAddFunction();
this.setState({ userEmail })
this.getResumeVideo(userEmail);
this.getDemoVideo();
this.getClass();
this.setState({
userEmail,
name,
profilePicture,
userID
})
this.getNotificationCount(userID);
Orientation.lockToPortrait();
this._unsubscribe = this.props.navigation.addListener('focus', () => {
this.getAddFunction();
this.getDemoVideo();
this.getResumeVideo(this.state.userEmail);
this.getClass();
this.getNotificationCount(userID);
});
}
The only place you are calling setState and tells react it should assign new value to state (and render...) it at componentDidMount, therefore React don't know it should render again.
When assigning new value to AsyncStorage you might also call setState
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
// here
this.setState({
name,
profilePicture,
userID
})
})
.catch((error) => {
console.log(error);
})
}
I am trying to login using PHP in react native so I am using fetch api but when I try to login it's always saying fields are blank whereas it's not. Can somebody help me with this?
Code:
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
Username: '',
Password: '',
}
}
login = () => {
const {
Username,
Password
} = this.state;
var payload = {
username: Username,
password: Password
};
this.state[payload];
var data = new FormData();
data.append("json", JSON.stringify(payload));
fetch("http://example.com/api.php", {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: data
})
.then(function(res) {
return res.json();
})
.then(function(data) {
alert(JSON.stringify(data))
})
.catch((error) => {
console.error(error);
});
}
}
Text input:
<TextInput
style={styles.input}
placeholder={'Username'}
placeholderTextColor={'#fff'}
underlineColorAndroid='transparent'
onChangeText={Username => this.setState({ Username })}
/>
<TextInput
style={styles.input}
placeholder={'Password'}
secureTextEntry={this.state.showPass}
placeholderTextColor={'#fff'}
underlineColorAndroid='transparent'
onChangeText={Password => this.setState({ Password })}
/>
If the name and password status value are not empty, try this.
let data = new FormData();
data.append("username", this.state.Username);
data.append("password", this.state.Password);
fetch("http://example.com/api.php",{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data
}).then((response) => response.json())
.then((res) => {
console.log(res);
}).catch(err => {
console.log(err)
})
});
OR
If you're trying to get him to JSON:
fetch("http://example.com/api.php",{
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.Username,
password: this.state.Password,
}),
}).then((response) => response.json())
.then((res) => {
console.log(res);
}).catch(err => {
console.log(err)
})
});
Since you are sending a request of type application/json, you should send the data directly as a JSON string:
var data = JSON.stringify(payload);
handleSubmit = e => {
e.preventDefault();
var data = new FormData();
data.append( "name", this.state.first_name + ' ' +this.state.last_name);
data.append( "password", this.state.password);
data.append( "email", this.state.email);
data.append( "phone_no", this.state.phone_no);
console.log(data)
fetch("http://localhost:8080/register",{
method: "POST",
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(res => res.json())
.then(
(result) => {
if(result.status == 'failure'){
alert(result.data)
console.log(result)
}else {
this.setState({
isLoaded: true,
});
}
// this.props.history.push('/dashboard');
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
the expected data should be something like
{ name: 'mayank', email: 'demo#gmail.com', password: 'password' }
what it is returning is
{ '------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form-data; name': '"name"\r\n\r\ nMayank nauriyal\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form-data; name ="password"\r\n\r\npassword\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form -data; name="email"\r\n\r\nma#gmail.com\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Dispo sition: form-data; name="phone_no"\r\n\r\n\r\n------WebKitFormBoundarynYkonogmAGuTwWsy--\r\n' }
Send JSON instead of FormData:
var jsObject = {name: 'John', password: 'foo', email: 'foo#bar.com'};
fetch(url, {
method: 'POST',
body: JSON.stringify(jsObject),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));