How can I send data to the server and get a response using my own application?
I am trying to learn how to react natively by creating a simple login page using an api call. Where will I post the username and password to the api and this will give me the answer. But I cannot do this. Well, I am sharing my code here .....
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
I think the path of passing my username and password to the server is wrong. Please give me some idea, then I can figure out what is wrong here.
+3
source to share
4 answers
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
Hope this helps.
+5
source to share
You need Stringify json data to send the request as a Post method with Json parameters, as you are trying to do ... Here is a sample code for how to encode the data before requesting a response
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
+1
source to share
Here is some sample code for login:
fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ userName: <userName> ,Password: <Password>,})
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
}).catch((error) => {
console.log("Error");
});
0
user7780118
source
to share