i have an issue with POST request inside my app.
part of code :
if (imagesResults !== undefined) {
imagesResults.forEach((el) => {
let localUri = el.uri;
let filename = localUri.split("/").pop();
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
formData.append("saleImages[]", {
uri: localUri,
name: filename,
type: type,
});
});
}
console.log("FORMDATA", formData);
const axiosConfig = {
headers: {
Authorization: "Bearer " + user.token,
"content-type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
};
try {
axios
.post(`${API}/sales/${saleId}/edit`, formData, axiosConfig)
.then((res) => {
// console.log("RES", JSON.stringify(res.data));
bottomSheetRef.current.snapToIndex(0);
setTimeout(() => {
bottomSheetRef.current.close();
dispatch(setLoadingApiAction(false));
navigation.navigate("My Ads");
}, 3000);
})
.catch((err) => {
console.log("error", err);
// setErrors(err.response.data.errors);
navigation.navigate("My Ads");
alert("SOMETHING IS WRONG!");
dispatch(setLoadingApiAction(false));
});
} catch (error) {
console.log("ERROR CATCH", error);
dispatch(setLoadingApiAction(false));
}
};
so what is happening, i fire my API, and i get 200 but just after i get 200 it return me also a network error and goes into .catch part.
This is only happening in ANDROID DEVICE , IOS working totally fine.
I am using a HTTPS , also i tried to set type of the image hardcoded into "image/jpeg" but i got the same problem.
Related
status: 500, error: "Internal Server Error"
message: Could not extract response: no suitable HttpMessageConverter found for response type [class com.clone.instagram.authservice.fetchdata.model.Example] and content type [text/html;charset=utf-8]"
So strangely this error has started showing up while accessing insta API,
What's strange is this happens "only sometimes",
And never happened before.
It works some times, some times it pops this error
const request = (options) => {
const headers = new Headers();
headers.append("Content-Type", "application/json");
if (localStorage.getItem("accessToken")) {
headers.append(
"Authorization",
"Bearer " + localStorage.getItem("accessToken")
);
}
const defaults = { headers: headers };
options = Object.assign({}, defaults, options);
return fetch(options.url, options).then((response) =>
response.json().then((json) => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
})
);
};
export function registerInstaUserInfo(instaUserINfoRequest){
if (!localStorage.getItem("accessToken")) {
return Promise.reject("No access token set.");
}
console.log("inside getInstaUserInfo request ");
return request({
url: properties.INSTA_USER_REGISTER ,
method: "POST",
body: JSON.stringify(instaUserINfoRequest),
});
}
const getInstaUserInfoFromService = (response) => {
//store respose.data
if (response.data.user_id) {
console.log("setting up insta user staate ", response.data);
localStorage.setItem("insta_user", response.data);
cookies.set("insta_user", response.data, { path: "/" });
console.log("cookies ", cookies.get("insta_user"));
const fb_access_token = localStorage.getItem("accessToken");
console.log("fb_access_token", fb_access_token);
const user_info = registerInstaUserInfo(response.data)
.then((res) => {
console.log(res);
setLinkedInstaAccounts([...linkedAccounts, res]);
})
.catch((err) => console.error("Hello stackoverlflowpeople this is where error happens", err));
console.log("user_info", user_info);
props.history.push("/home");
//redirecting to account.js
// props.history.push("/me");
}
};
const successResponse = (code) => {
console.log("inside success func");
console.log(code);
var bodyFormData = new FormData();
bodyFormData.append("redirect_uri", properties.INSTA_REDIRECT_URL);
bodyFormData.append("code", code);
bodyFormData.append("client_id", properties.INSTA_CLIENT_ID);
bodyFormData.append("client_secret", properties.INSTA_CLIENT_SECRECT);
bodyFormData.append("grant_type", "authorization_code");
axios({
method: "post",
url: properties.INSTA_ACCESS_TOKEN_URL,
data: bodyFormData,
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/vnd.api+json",
},
})
.then(getInstaUserInfoFromService)
.catch(function (response) {
//handle error
console.log(response);
});
};
----
//component
<InstagramLogin
clientId={properties.INSTA_CLIENT_ID}
buttonText="Login"
redirectUri={properties.INSTA_REDIRECT_URL}
scope="user_profile,user_media"
onSuccess={successResponse}
onFailure={failedresponseInstagram}
/>
=====================THIS getInstaUserFromService is where error happens
const getInstaUserInfoFromService = (response) => {
//store respose.data
if (response.data.user_id) {
console.log("setting up insta user staate ", response.data);
localStorage.setItem("insta_user", response.data);
cookies.set("insta_user", response.data, { path: "/" });
console.log("cookies ", cookies.get("insta_user"));
const fb_access_token = localStorage.getItem("accessToken");
console.log("fb_access_token", fb_access_token);
const user_info = registerInstaUserInfo(response.data)
.then((res) => {
console.log(res);
setLinkedInstaAccounts([...linkedAccounts, res]);
})
.catch((err) => console.error("Hello stackoverlflowpeople this is where error happens", err));
console.log("user_info", user_info);
props.history.push("/home");
//redirecting to account.js
// props.history.push("/me");
}
};
I was using this but I have not touched headers or anything, is it something with Instagram server?
I'm trying to patch data to a django API using axios using this snippet:
nextQuestion = () => {
if (this.state.currentIndex === 0) return;
const token = this.props.token;
const configs = {
headers: {
Authorization: `Token ${token}`,
},
data: {
quiztaker: this.state.data[0].quiz.quiztakers_set.id,
question: this.state.data[0].quiz.question_set[this.state.currentIndex]
.id,
answer: Number(this.state.answer),
},
};
console.log(configs);
axios
.patch("/api/save-answer/", configs)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
this.setState({
currentIndex: this.state.currentIndex - 1
});
};
I have confirmed that the token does indeed exist and that it is authorised to access and make changes to that endpoint through insomnia. Did i do anything wrong with how i set up axios? or is there something else i'm not getting? Apologies if it's an obvious mistake, still quite new to react.
With axios.patch() it should be executed axios.patch(url, data, config)....
const data = {
"quiztaker": this.state.data[0].quiz.quiztakers_set.id,
"question": this.state.data[0].quiz.question_set[this.state.currentIndex].id,
"answer": Number(this.state.answer),
};
const token = this.props.token;
const configs = {
"headers": {
"Authorization": `Token ${token}`,
},
};
axios
.patch("/api/save-answer/", data, configs)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
Get all contacts from phonebook and upload to server but got following error.
While append image in request body FormData
Tried code
pass file url contact thumbnailPath
const path = con.thumbnailPath
body.append('image', {
uri: path,
type: 'image/jpeg',
name: 'photo.jpg',
type: 'multipart/form-data'
})
Tried code
pass file url contact thumbnailPath without "file://"
const path = con.thumbnailPath.replace('file://', '')
body.append('image', {
uri: path,
type: 'image/jpeg',
name: 'photo.jpg',
type: 'multipart/form-data'
})
Tried code
check file exist on path or not with using react-native-fs
if (con.thumbnailPath != '') {
let isExist = RNFS.exists(con.thumbnailPath)
if (isExist) {
const path = con.thumbnailPath.replace('file://', '')
console.log("Exist", path)
body.append('image', {
uri: path,
type: 'image/jpeg',
name: 'photo.jpg',
type: 'multipart/form-data'
})
}
}
Request
fetch(url, {
method: 'POST',
headers: {
'Authorization': token,
'token': token
},
body: params
})
.then((res) => res.json())
.then((json) => {
console.log("RESPONSE:- ", json)
if (json.response[0].status == 'false') {
let msg = json.response[0].response_msg
callback(new Error(msg), json.response[0])
}
else {
callback(null, json.response[0])
}
})
.catch((err) => {
console.log(err)
callback(err, null)
})
The issues comes from react-native#0.63.2's internal bug.
A quick solution is to revert this commit: https://github.com/facebook/react-native/commit/31980094107ed37f8de70972dbcc319cc9a26339#diff-9a034658197479288c4d346a0eb4d98c
After manually revert this commit in node_modules, recompile the app and the image uploading will be working without any issues.
Replace the function loadImageForURL in /Libraries/Image/RCTLocalAssetImageLoader.mm with the following:
- (RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
size:(CGSize)size
scale:(CGFloat)scale
resizeMode:(RCTResizeMode)resizeMode
progressHandler:(RCTImageLoaderProgressBlock)progressHandler
partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
{
__block auto cancelled = std::make_shared<std::atomic<bool>>(false);
RCTExecuteOnMainQueue(^{
if (cancelled->load()) {
return;
}
UIImage *image = RCTImageFromLocalAssetURL(imageURL);
if (image) {
if (progressHandler) {
progressHandler(1, 1);
}
completionHandler(nil, image);
} else {
NSString *message = [NSString stringWithFormat:#"Could not find image %#", imageURL];
RCTLogWarn(#"%#", message);
completionHandler(RCTErrorWithMessage(message), nil);
}
});
return ^{
cancelled->store(true);
};
}
This problem is fixed in 0.63.3 ✅
**For IOS** in
node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm file
**Replace Below**
- -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
size:(CGSize)size
scale:(CGFloat)scale
resizeMode:(RCTResizeMode)resizeMode
progressHandler:(RCTImageLoaderProgressBlock)progressHandler
partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
{
UIImage *image = RCTImageFromLocalAssetURL(imageURL);
if (image) {
if (progressHandler) {
progressHandler(1, 1);
}
completionHandler(nil, image);
} else {
NSString *message = [NSString stringWithFormat:#"Could not find image %#", imageURL];
RCTLogWarn(#"%#", message);
completionHandler(RCTErrorWithMessage(message), nil);
}
return nil;
}
**With**
- -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
size:(CGSize)size
scale:(CGFloat)scale
resizeMode:(RCTResizeMode)resizeMode
progressHandler:(RCTImageLoaderProgressBlock)progressHandler
partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
{
__block auto cancelled = std::make_shared<std::atomic<bool>>(false);
RCTExecuteOnMainQueue(^{
if (cancelled->load()) {
return;
}
UIImage *image = RCTImageFromLocalAssetURL(imageURL);
if (image) {
if (progressHandler) {
progressHandler(1, 1);
}
completionHandler(nil, image);
} else {
NSString *message = [NSString stringWithFormat:#"Could not find image %#", imageURL];
RCTLogWarn(#"%#", message);
completionHandler(RCTErrorWithMessage(message), nil);
}
});
return ^{
cancelled->store(true);
};
}
This..
Like and Love , if it work
I have the same issue which perfectly reproducible on one of the iPhone 7 on my react-native project. It's strange but another iPhone 7's works perfectly as well as all Android devices.
My code:
formdata.append("file", {uri: photo.uri, name: name_img, type: 'image/jpeg' });
axios({
url: `${API}${'/upload'}`,
method: 'post',
headers: {
'Authorization': 'Basic ' + auth_token,
'Content-Type':'application/x-www-form-urlencoded'
},
data: formdata
}).then(response => this.saveRoute())
.catch(err => {
this.props.errorMessage({message: err})
}
})
Few things that I investigate:
I was not able to catch it in debug mode (seams smth wrong in async calls?)
I was not able to catch it with try-catch statement but seams it happened in Axios call.
So, I tried to play with Timeout and was able to make it totally unreproducible with 300ms timeout before Axios call.
formdata.append("file", {uri: photo.uri, name: name_img, type: 'image/jpeg' });
setTimeout(() =>
axios({
url: `${API}${'/upload'}`,
method: 'post',
headers: {
'Authorization': 'Basic ' + auth_token,
'Content-Type':'application/x-www-form-urlencoded'
},
data: formdata
}).then(response => this.saveRoute())
.catch(err => {
this.props.errorMessage({message: err})
}
})
, 300);
I know that it's a workaround but may help others to understand the issue for more deep research.
I temporary fixed using rn-fetch-blob, but the issue is present in 0.63.2 version and I didn't want to patch node_modules react-native images library.
To send file, you have to create a FormData and append your file into it. See EX: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Uploading_a_file
I found solution. Just put delay when you post request.
let options = {}
options.headers = headers
options.method = 'POST'
let url = {SERVER_URL}
options.body = new FormData();
for (let key in data) {
options.body.append(key, data[key]);
}
setTimeout(() => {
fetch(url, options)
.then((response) => response.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error) => {
let errParam = {}
errParam.errMsg = error.toString()
console.log(errParam)
resolve(errParam);
})
}, 1000);
Error fixed when updating React Native to version 0.63.3
I've tried to run my React Native on android and everything looks good while getting data from rest API,
but I dont know why when I want to send data into rest API the console log tell me
W/unknown:InspectorPackagerConnection: Couldn't connect to packager, will silently retry
here's the code I've tried :
try {
console.log(Constants.APILink + `DoAudit/PostCompleteAuditSchedulev1`, header + `token`)
axios.post(Constants.APILink + `DoAudit/PostCompleteAuditSchedulev1`, header, {
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer " + Queries.getPersistentData('token')
}
})
// NEVER RUN TO THIS STATEMENT OR SHOWING ME AN ERROR IN LOGCAT
.then(res => {
if (res.data == 0) {
console.log("Upload success HEADER");
var path = '/storage/emulated/0/Documents' + '/testx.txt';
RNFS.writeFile(path, JSON.stringify(mediaListFinding + auditid), 'ascii')
.then((success) => {
console.log('FILE WRITTEN!');
let dataAdd = NativeModules.SqliteModule;
dataAdd.insert(mediaListFinding, 0, auditid, function (value){
console.log("Service callback insert " + value);
})
})
.catch((err) => {
console.log(err.message);
});
this.setState({
loaderStatus: false
})
}
})
.catch((error) => {
console.log(error)
this.setState({
loaderStatus: false
})
});
} catch (error) {
console.log(error)
this.setState({
loaderStatus: false
})
}
I've tried to catch every error and using console to tell me what happen, but the logcat just showing me this:
next log never seeking
Upload Success HEADER or Error catch
Is there a way to upload video to a server in react native?
I've looked into the react-native-uploader plugin on github, but it doesn't give any guidance on video uploads if it's even possible with that plugin.
Just use fetch for uploading
let formData = new FormData();
formData.append("videoFile", {
name: name.mp4,
uri: video.uri,
type: 'video/mp4'
});
formData.append("id", "1234567");
try {
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
});
return await response.json();
}
catch (error) {
console.log('error : ' + error);
return error;
}
Here is another answer, using rn-fetch-blob in RN 0.57.8.
postVideo = (video,url) => {
RNFetchBlob.fetch('POST',url, {
'content-type': 'multipart/form-data',
"Accept":"multipart/form-data",
'access-token': AuthToken.token, //token from server
},[
//the value of name depends on the key from server
{name: 'video', filename: 'vid.mp4', data: RNFetchBlob.wrap(video.uri) },
]).then(response => response.json())
.then(response => {
if (response.status === 'success') {
alert("Upload success");
this.props.navigation.navigate('publish');
} else {
alert(response.msg);
}})
.catch((err) => {
alert(err);
})
}
Yes, it is possible.
you have to be running React Native 0.45.0 or higher, which do support accessing videos from camera roll.
you have to receive reference to image/video access from camera roll by calling CameraRoll.getPhotos(params) (more on this in docs)
then, use RNUploader.upload(...) to send assets to your serve (you need to link lib before!)