fetch api always getting fields are blank - javascript

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

Related

Display js Data in div Html

I want to display data I got from this code in console log (it's in JSON) and display it inside HTML. Which method shall I use?
async function getAVA() {
fetch('https://graphql.avascan.info', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query {
stats {
priceAvaxUsd
}
}`
}),
})
.then((res) => res.json())
.then((result) => console.log(result));
}
getAVA();
async function getAVA() {
fetch('https://graphql.avascan.info', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `query {stats {priceAvaxUsd}}`
}),
})
.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.data.stats.priceAvaxUsd;
})
.catch(error => {
console.log(error);
})
}
getAVA();
<div id="result"></div>

Using Fetch API to create a Login form

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

Is this a sound implementation of a signup function?

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
}

AsyncStorage works only when app is reloaded

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

fetch is sending wrong data fromat to backend

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

Categories