I'm trying to fetch data and access it later from an api that involves token authorization. The token will be generating in other places. this is the current fetch method and the error I have. Please help, been stuck here for days.
async getUserToken() {
const userData = await AsyncStorage.getItem("userData")
let data = JSON.parse(userData as string);
let dataString = data._W.token as string
return dataString
}
//fetch file from api here
async componentDidMount(){
try {
const response = await fetch(SOME_RANDOM_API), {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token' +
await this.getUserToken(),
},
body: JSON.stringify({
document: this.state.document,
name: this.state.name,
size: this.state.size,
file_type: this.state.file_type,
uploaded: this.state.uploaded,
})
})
const responseJson = await response.json();
console.log(responseJson)
// console.log("response is"+ responseJson)
this.setState({
isLoading: false,
dataSource: responseJson,
});
console.log("response 2 is"+ responseJson)
} catch (error) {
console.log("error is"+ error);
}
}
error here
Object {
"detail": "Unsupported media type \"application/json\" in request.",
}
error isTypeError: undefined is not a function (near '...this.state.dataSource.map...')
TypeError: undefined is not a function (near '...this.state.dataSource.map...')
Related
Showing network error when i call the post api in react native and i am using axios.
Here is my code
export const walletRequest = async () => {
let config = {
headers: {
userID: 'BLOCALEVIG',
password: 'bloc#!2#22ev!g',
'Content-type': 'Application/json',
Accept: 'Application/json',
},
};
let data = {
mfsapiin: {
ReqService: 'WAL_API_WALLETSCREEN',
mobileNumber: '8639833477',
},
};
let url = `https://app.blocal.co.in:5959/mfmbs/mbintf/ina/processwalletapirequest.jsp?mfsapiin={
"ReqService":"WAL_API_WALLETSCREEN",
"mobileNumber":"8639833477"
}`;
const walletCheck = await axios
.post(url, data, config)
.then(resp => console.log('walletRequest.resp', resp))
.catch(error => console.log('walletRequest.err', error));
console.log('walletCheck', walletCheck);
};
Kindly tell me what is wrong in my code
async signIn() {
try {
let response = await fetch(URI + '/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
});
let responseJson = await response.json();
if (response.status >= 200 && response.status < 300) {
let access_token = responseJson.access_token;
console.log(responseJson.access_token);
//On success we will store the access_token in the AsyncStorage
this.storeToken(responseJson.access_token);
this.props.navigation.navigate('Home',{AccessToken:access_token});
//this.props.navigation.navigate('Home');
} else {
//Handle error
let errors = responseJson.errors;
if (errors) {
let err = JSON.stringify(errors);
throw err;
}else{
let error = responseJson.error;
let err = JSON.stringify(error);
throw err;
}
}
} catch(error) {
this.setState({err: error});
console.log("error " + error);
}
}
Day wisely the react-native is updated and new methods were implemented.
using these codes day before was running but now the error pop ups ,now i can't fix these code . please let me know why these happpens
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 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)})
I am retrieving an image file from my api via my react front end. I am unsure how I can display the image once it is returned as my component receive a response with a blob promise that has not resolved when the component mounts.
Here is my backend api using express.js, specifically the part responding with the file that was earlier saved using multer.
Pet.findOne({_id : req.params.petId}, function(err, pet) {
if(err)return next(err);
if(!pet){
return res.status(400).json({message:"Pet not found", success: false});
}
res.sendFile(pet.profilePicturePath, {root : './'});
});
This finds the pets image from the mongodb and then uses express' sendFile method to respond to my front end request here:
fetch('/api'+nextState.location.pathname,{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({
token: tokenFound
})
})
.then((res)=>{
if(res.error){
browserHistory.push('/login')
}
return res;
}).then((json) =>{
if(json.success === false){
browserHistory.push('/login');
}else{
localStorage.setItem('token', tokenFound);
nextState.routes.json = json;
}
}).then((blob) => {
nextState.routes.blob = blob;
cb();
})
.catch(err => console.log('Error token: ' + err));
}else{
browserHistory.push('/login');
cb();
}
When I go to my component, PetPage, that calls the above function onEnter '' I am not sure how to display the image file that I receive.