Can not get image from api when using http-proxy-middleware in React.Js - reactjs

i got cors error and fixed it when using http-proxy-middleware according to video tutorial https://www.youtube.com/watch?v=hxyp_LkKDdk (Skip to solution: 20:08, i have followed and it is like below). everything is fine until i get the picture from the api. Did I miss something?
here's my setupProxy.js
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
// GET Image
app.use(
"/file/",
createProxyMiddleware({
target: "https://.....",
changeOrigin: true,
})
);
};
and user.js
const loadImage = () => {
setLgShow(true);
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer abcdefghiklm");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow",
};
fetch(`/file/${user.img_front_file_id}`, requestOptions)
.then((response) => response.text())
.then((result) => {
console.log(result);
imagRef.current = result;
console.log(JSON.parse(result));
})
.catch((error) => console.log("error", error));
};
and the binary trash (the response when I call API image)
I finally found the answer
const res = await axios({ url: `/file/${user.img_front_file_id}`, method: "GET", headers: { Authorization: "Bearer eFS3oJaQhRU1c5EajQUL", "Content-Type": "application/json", }, responseType: "blob", });
const file = new Blob([res.data], { type: "image/jpg" });
const url = URL.createObjectURL(file); imagFontRef.current = url;
setFinishFront(true); console.log(res);

Related

Discord Vanity Sniper

const request = require('request');
let token = '';
let server = '';
const url = {
url: `https://discord.com/api/v10/guilds/${server}/vanity-url`,
method: "PATCH",
headers: {
Authorization: `User ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo231",
}),
};
request(url, (err, res, body) => {
if (err) return console.log(err);
console.log(body);
})
I am trying to make a vanity sniper but only 401... any help would be overly appreciated.

Downloading a video from an API in React using Axios creates an empty mp4 file

I have a backend api that returns a video (verified route in Postman) but when trying to implement a "download video" button, it downloads an empty file
I've tried multiple implementations with at best identical results but here is the current code:
const handleDownloadVideo = async () => {
const axios = require('axios');
const config = {
method: 'get',
url: `http://localhost:3001/api/v1/render/video/${UUID}/download/`,
headers: {
'Authorization': 'Bearer {token}',
'responseType': 'blob',
'maxContentLength': Infinity,
'maxBodyLength': Infinity
}
};
axios(config)
.then((response) => {
const link = document.createElement('a');
link.target = '_blank';
link.download = `${UUID}.mp4`;
link.href = URL.createObjectURL(new Blob([response.data], { type: "video/mp4" }));
link.click();
})
.catch(function (error) {
console.error(error);
});
};
I wouldn't expect this to be a difficult task and yet have been struggling with it for multiple days now. Can anybody explain what I'm doing wrong here?
Don't know if this might solve the problem, but your request config responseType, maxContentLength and maxBodyLength should be outside the header object.
const config = {
method: 'get',
url: `http://localhost:3001/api/v1/render/video/${UUID}/download/`,
responseType: 'blob',
maxContentLength: Infinity,
maxBodyLength: Infinity
headers: {
'Authorization': 'Bearer {token}'
}
};

react native post form data with object and file in it using axios

so i want to upload
object as data
and file as Note
to api using axios
uploadToServer= () => {
const file =this.state.photo
let data2 ={sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')
data.append('data[description]', "test")
data.append('data[note_content_item]', "test")
console.log(data)
axios({
url: api',
method: 'POST',
data: data,
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(resp => console.log(resp.data.response))
.catch(error => console.error(error));
}
first i am trying with data without Note i can do it in postman
but with my code i got error
message: "Can not save file"
response_code: 10
i got this error only if i change the key from data to something else
when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.
second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.
import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;
const axiosInstance = axios.create({
baseURL: 'example.com', // use with scheme
timeout: 30000,
headers: {
"X-Platform": 'iOS',
"X-App-Build-Number": '1.0.0',
},
});
const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
uri: "/dev/sda/abc.png",
type: "image/png",
name: "abc.png",
});
const config: AxiosRequestConfig = {
method: "post",
url: "/process/start",
responseType: "json",
headers: {
'Content-Type': 'multipart/form-data',
// if backend supports u can use gzip request encoding
// "Content-Encoding": "gzip",
},
transformRequest: (data, headers) => {
// !!! override data to return formData
// since axios converts that to string
return formData;
},
onUploadProgress: (progressEvent) => {
// use upload data, since it's an upload progress
// iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
},
data: formData,
};
// send post request and get response
const response = await axiosInstance.request(config);
You are not building FormData correctly, Try this:
let data = {sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
uri: "file://" //Your Image File Path
type: 'image/jpeg',
name: "imagename.jpg",
});
axios({
url : api,
method : 'POST',
data : formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(function (response) {
console.log("response :", response);
})
.catch(function (error) {
console.log("error from image :");
})
This might help you:
import {Platform} from 'react-native';
import axios from 'axios';
const upload = async readPath => {
console.log('path', readPath);
const URL = 'your-url';
const headers = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
Authorization: `Bearer ${projectSecret}`,
},
};
const formData = new FormData();
const file = {
uri:
Platform.OS === 'android' ? `file:///${readPath}` : readPath,
type: 'text/plain',
name: name,
};
formData.append('file', file);
await axios
.post(URL, formData, headers, {
timeout: 3000,
})
.then(async response => {
console.log(response.data);
})
.catch(error => {
console.log('error : ', error);
});
};

How to use post method in react native?

constructor(props) {
super(props);
this.state = {text: this.props.navigation.state.params.text,
name:this.props.navigation.state.params.name};
}
manage = () => {
Alert.alert('done')
Actions.reset('mainScreen');
fetch("http://ip/api/confirm", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.props.navigation.state.params.name,
text:this.props.navigation.state.params.text
})
})
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
i want to do this
when i press in button go to manage function
and post the text and the name to my api i dont know how can i pass them
its give me this error :
network request failed
any help please
I recommend you to use axios to make network requests.
Installing:
npm i -S axios
Performing a POST request:
import axios from 'axios';
axios({
url: 'http://ip/api/confirm',
method: 'post',
data: {
name: this.props.navigation.state.params.name,
text: this.props.navigation.state.params.text,
},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
var resp = await manage(this.props.session.userId,this.props.session.ApiKey,"hi","hello");
if (resp.status == 200){
var respBody = await resp.json();
console.log('Fetch Todo response '+respBody);
}
API in separate file
export async function manage(userId,ApiKey,query,query1) {
var url ="http://www.example.com/getdata";
const params = {
search:query,
searches:query1
};
var formBody = [];
for (const property in params) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(params[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
const requestOptions = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'application/json'
},
'body': formBody
};
requestOptions.headers["userid"] = userId
requestOptions.headers["apikey"] = ApiKey
try {
var resp = await fetch(url, requestOptions);
return resp;
}
catch (err) {
console.log("Request Failed: " + err);
return err;
}
}

React-Native image upload

Is it possible to upload file (images) to server with react-native using FormData? Tried to use it like this:
var data = new FormData();
data.append('file', file);
console.log(JSON.stringify(data));
var id = 5;
fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id,{
method:'POST',
body: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;',
},
});
For React, FormData works as expected but for React-Native not working.
I have also tried (used in react - working)
const data = fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id, {
credentials: "same-origin",
method:'POST',
body: dataval,
timeout: 1000000000,
});
But nothing works,
In the back-end server, I am upload using
var d = require('domain').create()
d.run(function safelyUpload () {
var file=req.file('file').upload({dirname: path.resolve(sails.config.appPath, folder),
}, function whenDone(err, uploadedFiles) {
if (err) return res.serverError(err);
else{
sails.log.debug('Complaint File data : ' +util.inspect(uploadedFiles, {showHidden: true,depth: null}));
}
});
});
Is there any other ways
Here is example to upload image using Fetch API
const photo = {
uri: user.profilePicture,
type: 'image/jpeg',
name: 'photo.jpg',
};
const form = new FormData();
form.append("ProfilePicture", photo);
fetch(
URL,
{
body: form,
method: "PUT",
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + user.token
}
}
).then((response) => response.json())
.catch((error) => {
alert("ERROR " + error)
})
.then((responseData) => {
alert("Succes "+ responseData)
}).done();
Credits https://stackoverflow.com/a/36649457/5315786

Resources