How to fetch data in react native? - react-native

I need to fetch data from pass parameter in below format, because when test in Postman then only this format gives response.
"json": {"model":"DB11 AMR","modelyear":"2019","locale":"AA"}
Can you please help to fetch data from below server url.
https://vhapp.azurewebsites.net/myAMLModelSelection
Below is my code
var url = 'http://vhapp.azurewebsites.net/myAMLModelSelection'
try {
let response = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"json" : { "locale": "AA", "model" : "DB11 AMR", "modelyear" : "2019" }
})
})
.then(res => res.text()) // convert to plain text
.then(text => {
console.log(text)
alert(text)
var res = text.substring(1, text.length-2);
var obj = JSON.parse(res);
alert(obj.cars[0].name)
})
.catch((error) => {
console.error(error);
});
} catch (errors) {
console.log(errors);
}
Here is my response which i need
({"cars":[{"name":"DB11 AMR","content":{"guide":"http://cdntbs.astonmartin.com/360ss/OwnersGuides/KY53-19A321-AC.pdf","assets":[{"intAssetId":"115","intVehicleId":"1","strType":"pdf","strName":"Accessories Brochure","strDescription":null,"strLocation":"http://cdntbs.astonmartin.com/360ss/iPad/myaml/brochures/Accessories Brochure English - 706435-PK.pdf","intVersion":"1","intOrder":"1"}]}}]});

You can fetch the data using JS fetch API.
export async fetchMyData(){
try{
let f = await fetch('https://vhapp.azurewebsites.net/myAMLModelSelection',{method:'GET'})
let data = await f.json();
return data;
}catch(err){
console.log(err)
}
}
And Call this method in your component like:
import {fetchMyData} from './file_name'
fetchMyData().then((response)=>{console.log(response)})

Related

Hashnode API with GraphQL API resulting in error

I am trying to call the hasnode API to get blogs as the response, the body is in GraphQL. But I get this error in the Network Tab 'POST body missing. Did you forget use body-parser middleware?'
`
let query = `
{
user(username: "singhmona") {
publication {
posts{
slug
title
brief
coverImage
}
}
}
}
`;
let body = JSON.stringify({
query
});
axios
.post('https://api.hashnode.com/',
body,
{
'content-type': 'application/json',
})
.then(response => {
this.info = response;
console.log(response);}
)
`
I think you should try using fetch. I've had a tough one with axios when using it in node and I was finally able to get the api to work with fetch. Here is a snippet of what worked for me.
const getData = async() => {
const query = `
{
user(username: "misiochaabel") {
publication {
posts(page: 0) {
slug
title
brief
coverImage
}
}
}
}
`;
const response = await fetch('https://api.hashnode.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const data = await response.json();
console.log(data);
}

React native im trying to upload image everytime localuri.slpit not defined showing and {_parts:[[]]} and why this _parts coming while sending data

can anyone tell me what wrong with this code im trying to upload image using react-native-image-picker in react native.but it says localUri.split is not defined and sending data shows in inspect element as {_parts:[[]]} and why this _parts coming every post method ...please help me to figure out this..
const takeAndUploadPhotoAsync = async () => {
const token = await AsyncStorage.getItem("userToken");
let result = await launchImageLibrary();
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop().split('#')[0].split('?')[0]
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
const url = `/auth/upload-prescription`;
let formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
setLoading(true);
const response = await api
.post(url, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
showMessage({
message: "Your Prescription is Uploaded Successfully",
textStyle: {textAlign:'center'},
type: "success",
backgroundColor: "#202877",
});
})
.catch((error) => {
console.log(error.response);
});
dispatch({
type: "TAKE_AND_UPLOAD_PHOTO_ASYNC",
payload: response,
});
setLoading(false);
};

How to set formData for boolean in Axios post request

I'm trying send a post request using axios to my backend but I can't send the boolean "isActive" for some reason. Is there a way to do this?
async submit() {
const isValid = await this.$validator.validateAll()
if (isValid && !this.submitting) {
let formData = new FormData();
formData.set("city", this.formData.city)
formData.set("state", this.formData.state)
formData.set("county", this.formData.county)
formData.set("isActive", true) // <- NOT ACCEPTING THIS VALUE
axios.post("/api/v1/team/createTeam", formData, {
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.status === 200) {
this.submitting = true
this.cancelModal()
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}
}
FormData can only contain string values. Setting a Boolean true would result in "true" for the value. The backend would have to convert that string to a Boolean.
Also, your header should not be application/json (intended for JSON payloads). If sending FormData as the payload, the header should be multipart/form-data:
axios.post("/api/v1/team/createTeam", formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
If your backend is actually expecting JSON, then you can't send FormData. Switch to a JavaScript object instead (which does accept Booleans):
const payload = {
city: this.formData.city,
state: this.formData.state,
county: this.formData.county,
isActive: true,
}
axios.post("/api/v1/team/createTeam", payload, {
headers: {
'Content-Type': 'application/json'
}
})

React native with Asp.net Core photo upload

I want to upload photos with React Native. My API attempt from Postman resulted in a positive.
But React Native didn't make it.
React Native function
uploadPhoto = async response => {
const data = new FormData();
data.append("image", {
uri: response.uri,
type: response.type,
name: response.fileName,
length:response.fileSize
});
const config={
headers:{
'Content-type':'multipart/form-data'
}
}
axios
.post('https://localhost:44337/api/values',JSON.stringify(data),config)
.then(response=>{
console.log(response);
})
.catch(error=>{console.log(error);})
};
Asp.net Core side
[HttpPost]
public IActionResult Post([FromForm]PhotoModel bookData)
{
//installation codes
return Ok();
}
Model
public class PhotoModel
{
public IFormFile image { get; set; }
}
Result:Network Error
You can try in react native code.
Hope helpful for you.
export const uploadImages = async (formData) => {
try {
let response = await axios({
url: urlUploadImages,
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + global.TOKEN || 'Bearer ' + await AsyncStorage.getItem("#loggedInUserID:token"),
},
data: formData,
});
console.log('uploadImages API response', response)
if (response.status === 401) {
return global.UNAUTHORIZE;
} else {
// let json = await response;
if (response.status === 200) {
return response.data;
} else {
return global.FAIL;
}
}
} catch (error) {
console.log('Upload Failed', error);
}
};
You don't have to change from form data back to JsonString. Send it right away.
.post('https://localhost:44337/api/values',data,config)
Remove json.stringify and verify that you set right values:
const form = new FormData();
form.append('image', {
uri: "file:///...",
type: 'image/jpg',
name: 'image.jpg',
});

i am trying to fecth html page with react-native-html-parser

How to parse html page from fetch response?
I have checked both async and regular promise syntax but nothing seems to compile:
const fetch = require('node-fetch'); var DOMParser = require('react-native-html-parser').DOMParser;
function getbooks() {
fetch('https://github.github.io/fetch/').then(function(response) {
if (response) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
})
}
const books=getbooks();
console.log(books);
var DOMParser = require('react-native-html-parser').DOMParser;
var doc = new DOMParser().parseFromString(
books);
console.log(doc);
console.log('end');
What gets returned from your endpoint?
You Can try:
NOTE: Your trying to log a response from something that is asyncrhonus. You need to use
async and await (with promises). Something like...
async function getBooks(){
var response = await fetch('https://github.github.io/fetch/', {
method: 'GET',
headers: {
Accept: 'application/json',
},
}).then((response) => {console.log(response);return response})
.then((responseJson) => {
return responseJson.json();
})
.catch((error) => {
console.error(error);
return {error: "Couldn't get books"}
});
console.log(response);
}
getBooks();