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.
Related
Need assistance, I have gotten it right to have the POST API show the responses as it should.
I need assistance with getting these responses shown on the product pages on Shopify, as they are product qty's from the supplier. I am new at this so please be easy on me...
Running the API in VisualCode with Thunder Client.
Have the following JS running but dont know if i am on the right path, it is then linked to an html to actually show the results.
fetch("URL")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then(data => {
console.log(data);
display(data)
})
.catch((error) => {
return console.error("FETCH ERROR:", error);
});
const token = localStorage.getItem('token')
const response = await fetch(apiURL, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${ttoken}`,
}
})
My react native app crashes in .apk when fetch returns a bad request or network error
Below is the fetch function:
try {
const reponse = await fetch(
'http://example.com',
{
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body
},
);
if (reponse.ok) {
const data = await reponse.json();
console.warn('Success response', data);
return navigation.navigate('different', {
token: data.token,
memberNo: data.user.memberno,
});
} else {
setStatus('Incorrect Details entered');
// console.warn('Failed response', reponse);
}
} catch (error) {
setStatus('Network request failed connect to the internet');
// console.error('CATCH Error', error);
}
}```
First check you API response may be its return something null or undefined and you used that in your screen.
e.g when we use flatlist and pass undefined and null then the apk crash so focus on your data format
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...')
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 new to react-native. I am trying to pass the authorization token through a header in the GET method. But I am getting an unauthorized error.
I have already tried this code "Using an authorization header with Fetch in React Native" not working for me and also with XMLHttpRequest()
But the API works fine in postman, Java(core) and Android.
Do we have any special implementation in react-native to pass headers?
Could anyone can help me with this?
My code: Changed the server name.
getData() {
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://xyz-test-server.server.com/api/v3/users/details/");
xhr.setRequestHeader("Authorization", "Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2");
xhr.setRequestHeader("User-Agent", "PostmanRuntime/7.17.1");
xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
xhr.setRequestHeader("Accept", "*/*");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "d8ae56bf-1926-44e4-9e94-23223234,93a110a2-ee8e-42d5-9f7b-45645ddsfg45");
xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
xhr.setRequestHeader("Connection", "keep-alive");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
}
Fetch method:
async _getProtectedQuote() {
fetch('https://xyz-test-server.server.com/api/v3/users/details/', {
method: 'GET',
headers: new Headers({
'Authorization': 'Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2',
'Content-Type': 'application/x-www-form-urlencoded'
}),
}).then(responseJson => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
});
}
You can try interceptor for pass token into header.
Put all requests in one service file name service.js then import Interceptor from '../interceptor';
make one interceptor.js file and write below code in file.
import axios from 'axios';
axios.interceptors.request.use(async (config) => {
if (config.method !== 'OPTIONS') {
config.headers.Authorization = 'Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2';
}
return config;
}, function (error) {
// Do something with request error
console.log('how are you error: ', error);
return promise.reject(error);
});
axios.interceptors.response.use(
(response) => {
return response
},
async (error) => {
// const originalRequest = error.config
console.log("error in interceptors=============>", error);
if (error.response.status === 500) {
alert(error.response.data.message);
NavigationService.navigate('Login');
} else {
return Promise.reject(error)
}
}
)
export default axios;
When api calls header will pass through by interceptor automatically.
Fetch Api converts all headers into lower-case. We need to do case-insensitive server side parsing.