I am trying to get data from an api but the thing is the api has php extesnion. I am quite new to this thing and I really dont understand why i am not getting the data by using result.data.
var formdata = new FormData();
formdata.append("stock_symbol", "PPL");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch(url, requestOptions)
.then(response => response.text())
.then(
result => {
console.log('result', result.data)
}
)
.catch(error => console.log('error', error));
It does not matter from where you are fetching the data you are making a silly mistake, the data format is in json but you are forcibly converting it to raw text so you have to replace result.data with only result e.g.
var formdata = new FormData();
formdata.append("stock_symbol", "PPL");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch("https://dev-api.sarmaaya.pk/3.0/company_fundamentals.php", requestOptions)
.then(response => response.text())
.then(
result => {
console.log('result', result) //now works
}
)
.catch(error => console.log('error', error));
for request.data to work you have to replace response.text() with response.json()
var formdata = new FormData();
formdata.append("stock_symbol", "PPL");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch("https://dev-api.sarmaaya.pk/3.0/company_fundamentals.php", requestOptions)
.then(response => response.json())
.then(
result => {
console.log('result', result.data) //now it works
}
)
.catch(error => console.log('error', error));
Related
public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.map((res: { json: () => any; }) => res.json())
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
i want to post and get methond to backend but i cant fix this code
.map
this doesnt work,
if i could fix this .map method it will be done
You want to use RxJS map method.
For that you need to .pipe the observable stream like so:
public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.pipe(map((res: { json: () => any; }) => res.json()))
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
By default the Angular HttpClient will handle processing the JSON response for you. Assuming you are using this service, this means your map here is not necessary and can be removed entirely.
public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
If you do need the full response, such as the HTTP status code you can pass observe: 'response' into the options object the post function accepts. The Angular documentation goes into good detail on this.
As an FYI, in older versions of Angular that had a now deprecated service called Http and you would need to call .json() all the time.
I am new from here. Just stuck on some problem of fetching the data from frontend(react) to the raw value in JSON. For the login part, when I enter the email and password, supposedly the response are same as the result in POSTMAN, but i get the error. I am figure out this issue for almost oneweek. I would be appreciate for those who help me to solve on this issue. I will elaborate further on below about my situation:
Here is the response of API from postman (supposedly I should get this response):
The result I get in the browser:
Source Code:
constructor (props){
super(props);
this.state ={
loginEmail: '',
loginPassword: ''
}
this.login = this.login.bind(this);
this.onChange = this.onChange.bind(this);
}
login(){
PostData('api/users/login', this.state).then ((result) => {
let responseJSON = result;
console.log(responseJSON);
});
}
PostData:
export function PostData(type, userData = {}){
let BaseUrl = "https://ems-unimas-58134.herokuapp.com/"
return new Promise((resolve, reject) => {
fetch(BaseUrl+type,{
method: "POST",
body: JSON.stringify(userData),
Accept: 'application/json',
// headers:{
// 'Content-Type': 'application/json'
// }
}).then(res => res.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error)=>{
console.error('Error:', error);
})
});
}
Commend down here if anyone of you need more code.
The problem is you need to allow CORS.
You can read more about CORS in here
I am trying to connect my react app with the backend for log in page. I am using a promise to return a success message.
login.js
onSubmitSignIn = () => {
fetch('http://localhost:5000/', {
method : 'post',
headers :{ 'Content-Type' : 'application/json'},
body : JSON.stringify({
userId : this.state.userId,
password : this.state.password
}).then(response => response.json())
.then(data => {
if(data === 'success'){
this.props.onRouteChange('home');
}
})
})
}
Backend code -
exports.findById = (req) => {
return new Promise((resolve) => {
var sql = "Select * from users where userid = '" + req.body.userId + "' ;";
connection.query(sql,req, function (error, results, fields) {
var data = JSON.parse(JSON.stringify(results));
var valid = false;
if( data.length !=0 && req.body.userId === data[0].userid && req.body.password === data[0].password)
valid = true;
if(valid) {
resolve({message : "success"});
}else{
reject({ message :"fail"});
}
});
})
};
After clicking on sign in button, I am getting an error "TypeError: JSON.stringify(...).then is not a function"
I tried some solutions from similar questions, it did not work in my case.
The then should be outside of fetch
fetch('http://localhost:5000/', {
method : 'post',
headers :{ 'Content-Type' : 'application/json'},
body : JSON.stringify({
userId : this.state.userId,
password : this.state.password
})
}).then(response => response.json())
.then(data => {
if(data === 'success'){
this.props.onRouteChange('home');
}
})
You have a typo, .then should be on fetch not on JSON.stringify.
onSubmitSignIn = () => {
fetch("http://localhost:5000/", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: this.state.userId,
password: this.state.password
})
})
//-^
.then(response => response.json())
.then(data => {
if (data === "success") {
this.props.onRouteChange("home");
}
});
};
you have missed a bracket. there should be a closing bracket after JSON.stringify().
onSubmitSignIn = () => {
fetch('http://localhost:5000/', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: this.state.userId,
password: this.state.password
})
}).then(response => response.json())
.then((data) => {
if (data === 'success') {
this.props.onRouteChange('home');
}
});
};
I had this problem too. Check and confirm that you're not importing or requiring {JSON} in your application. It's most likely referring to that imported JSON rather than the global
I am trying to put three params in my post request to particular api but i didn't get the response as i expected. API works fine in my Postman but i am not sure about my fetching method in my react native app i am new to this so i don't know how to put headers in my api request i followed some docs but didn't get much please have a look and answer my question.
constructor (props) {
super (props)
this.state = {
detail: ''
}
}
ComponentDidMount(){
var data = new FormData();
data.append('mobile_number','8615351655')
data.append('mobile_country_code','+21')
data.append('rec_name','Shantanu Talwaar')
}
fetchData = async() => {
fetch('http://link.com/link/',
{
method: 'POST',
headers:{
//this what's exactly look in my postman
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;
},
body: this.data
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson.detail)
}).catch((error) => {
alert('error')})}
render() {
return (
<View style = {styles.container}>
<Button onPress = {this.fetchData} title = "fetch"/>
<Text style={styles.text}>Fetched data displays below</Text>
<Text style={styles.text}>{this.state.detail}</Text>
</View>
)
}
}
This is the result i am having right now in my alert box: "Authentication credentials were not provided."
There is a ' missing after your token.
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;
And as it is a JSON Object you should remove the semi-colon
So, the final code will be
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
There is also another problem. The data declaration is not accessible from the fetch function. So you should do something like this.
fetchData = async() => {
var data = new FormData();
data.append('mobile_number','8615351655')
data.append('mobile_country_code','+21')
data.append('rec_name','Shantanu Talwaar')
fetch('http://link.com/link/',
{
method: 'POST',
headers:{
//this what's exactly look in my postman
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
},
body: data
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson.detail)
}).catch((error) => {
alert('error')
})
}
i think you can use "x-access-token" as header name for authentication token and place Content-Type too.
fetchData = () => {
fetch('http://link.com/link/',
{
method: 'POST',
headers:{
'Content-Type': "application/json",
'x-access-token': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
},
body: this.data
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.detail)
}).catch((error) => {
alert('error')})
}
Here is my code.
I am calling the following function to get state list.
callGetStatesApi()
{
callGetApi(GLOBAL.BASE_URL + GLOBAL.Get_States)
.then((response) => {
// Continue your code here...
stateArray = result.data
Alert.alert('Alert!', stateArray)
});
}
Here is common callGetApi function for getting response from GET Api.
export function callGetApi(urlStr, params) {
return fetch(urlStr, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseData) => {
result = responseData
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
}
I am getting the following error.
Alert only show the string , but your case "stateArray" is complex object (array,structure..)
So use stateArray.toString() or JSON.stringify(stateArray),
Or
Try the below method and let me know,
fetch(GLOBAL.BASE_URL + GLOBAL.Get_States, {
method: 'get',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',}
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData) // this is the response from the server
// Continue your code here...
stateArray = result.data
Alert.alert('Alert!', stateArray)
}).catch((error) => {
console.log('Error');
});