Laravel Vapor Blob responses are empty - laravel-9

On my local environment the following works, but not on the Vapor instance. Connection to S3 is working, so that's not the issue.
return Storage::disk('s3')->download($s3Path, 'export.xls', [
'X-Vapor-Base64-Encode' => 'True',
]);
It should return a Blob response.
import FileDownload from "js-file-download";
function downloadFile() {
axios({
url: "/api/working-url",
method: "GET",
responseType: "blob",
})
.then((response) => {
FileDownload(response.data, "export.xls");
})
.catch((error) => console.error(error));
}
Locally it's working, so it's probably something I'm missing for the Vapor config.
When I download the file via Vapor, it's an empty file.

Related

React Native - Can't get data from asp.net web api

I'm building an app using React Native with Expo and an ASP.Net Web API.
I'm using two computers: one I published the Web API on it and using it as a server which has the IP 192.168.1.9 ,
and the other one with IP 192.168.1.6 I'm using for developing.
The problem is when I ping the server computer I get a reply and when I use postman I get the data I requested,
but when I run the app using Expo on my Android Phone, the request enters the catch and returns an error.
Here is the code:
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
})
.then(response => { response.json(); })
.then(users => {
this.setState({ allUsers: users });
})
.catch(error => console.error('Error getting users :: ', error));
I have tried everything I could possibly think of, but no use.
Can someone tell me what the problem is? thank you .
You can configure Accept and Content-Type of headers.
And get the correct value for the object.
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then(res => {
this.setState({ allUsers: res.Username });
})
.catch(error => console.error('Error getting users :: ', error));

has been blocked by CORS policy by using axios and fetch in react [duplicate]

This question already has answers here:
Axios having CORS issue
(12 answers)
Closed 3 years ago.
I'm trying to do a post request of a server but keep getting a CORS error using axios and fetch in React.
the code:
fetch('https://api/entries',
{ mode: 'no-cors',
method: 'post',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
body: JSON.stringify({
"KEY":"VALUE"
})
})
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
or
axios({
method: 'post',
url: 'https://api/entries',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
axios console response
Access to XMLHttpRequest at 'https://api/entries' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
and the another
Fetch console response
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api/entries with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Thanks
The best and easiest way is to tackle this problem is to use Proxy URL.
Like so
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios.post(PROXY_URL+URL)
.then( i => console.log(i) )
.catch(e => console.error( "Error occured! ", e));
in your case try using this like this: This should work.
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios({
method: 'post',
url: PROXY_URL+URL,
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
You can even use Proxy URL with fetch()
its depends on your backend
for example, if you use Django
you need to install https://github.com/ottoyiu/django-cors-headers
and add this CORS_ORIGIN_ALLOW_ALL=True in setting file

How to upload photos with React Native

node v10.14.1
npm v6.4.1
strapi v3.0.0#13.0.1
I'm trying to upload a picture taken with a "PhotoUpload" component to Strapi.
Despite various tests, I get an error 500 from the server.
Insert_Files_Into_DataBase = () => {
const formdata = new FormData();
formdata.append("files:", this.state.image1); //Base64
this.setState(
{
ActivityIndicator_Loading: true
},
() => {
fetch("" + NETWORK.SERVER_IP + ":1337/upload", {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + this.props.userToken.jwt
},
body: formdata
})
.then(response => response.json())
.then(responseJsonFromServer => {
alert(responseJsonFromServer + "Image1 OK!");
this.setState({ ActivityIndicator_Loading: false });
})
.catch(error => {
console.error(error);
this.setState({ ActivityIndicator_Loading: false });
});
}
);
};
My "PhotoUpload" component allows me to retrieve the Base64 from the image. But it doesn't seem to work.
With Postman, everything works correctly
Are you doing this on the iOS simulator? I find uploading only works for me on a real iOS device.
In your code above, you are appending files: (with extra colon (:)). I think, you should append just files in the FormData() as:
formdata.append("files", this.state.image1); //Base64
This might be the case you are getting 500. If not also, you should append files instead of files:.
If this solves your problem, don't forget to hit upvote. :)
I found a first mistake!
I had simply forgotten the "HTTP://" in the address of my server.
Now, the server sends me back "true" but the image is not actually uploaded

React Native fetch throws error when posting multipart/form-data

This is how I tried to POST an image as multipart/form-data to server.
var photo = { uri: this.state.avatarSource,
type: 'multipart/form-data',
name: 'photo.jpg', };
let formdata = new FormData();
formdata.append('attachment',photo);
fetch(url,
{ method: "POST",
headers: { 'Content-Type': 'multipart/form-data' },
body: formdata
}).then((response) => response.json())
.catch((error) => { alert("ERROR " + error) })
.then((responseData) => { alert("Succes "+ responseData) }).done();
But it shows an error : Expected dynamic type string but had type
object
After 2 days, trying so many things I made the code working with some modifications.
RNFetchBlob.fetch('POST', url, {
'Content-Type': 'multipart/form-data',
}, [
{ name: 'file', filename: 'photo.jpg', type: 'image/png', data: RNFetchBlob.wrap(src) }
]) .then((resp) => {
console.log(resp.text());
}).catch((err) => {
console.log(err);
});
As mentioned in the docs formData.append(name, value, filename);
The value field in it accepts USVString or Blob, since you're passing an object to it therefore it throws an error.
You need to convert your image to blob, append and upload it.
If you've got the base64 of the image, then you can convert it to a blob directly using the fetch api
fetch(base64URL)
.then(res => res.blob())
.then(blob => console.log(blob))
Otherwise you may checkout RN-fetch-blob, their multipart/ formData example.
I slightly modified the solution given by #unknown123. And it worked for me.
Here is the solution.
First, install npm package rn-fetch-blob
import RNFetchBlob from 'rn-fetch-blob';
RNFetchBlob.fetch('PUT', url, {'Content-Type': 'multipart/form-data'},
Platform.OS === 'ios' ? RNFetchBlob.wrap(filePath) :
`RNFetchBlob-${filePath}`)
Please note, in my case, I had different file paths for IOS and Android devices. We handle it in different ways using rn-fetch-blob
Sample filePath variable data for
IOS device -
"/Users/Niveditha/Library/Developer/CoreSimulator/Devices/B41EB910-F22B-4236-8286-E6BA3EA75C70/data/Containers/Data/Application/B88777C6-6B10-4095-AB67-BB11E045C1DE/tmp/react-native-image-crop-picker/img.jpg"
Android device -
"file:///storage/emulated/0/Android/data/com.uploadcameraroll/files/Pictures/img.jpg"

Aurelia: fetch-client response doesn't have my data

I've been banging my head against fetch-client for too long and I need some help.
I'm getting some data from Skyscanner. The request hits their API and Chrome's dev tools list it in the network tab as a complete fetch request with code 200 and the correct response body.
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
#inject(HttpClient)
export class Flights {
constructor(http){
http.configure(config => {
config
.withBaseUrl('http://partners.api.skyscanner.net/apiservices/')
.withDefaults({
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-type' : 'application/json'
}
});
});
this.data = "";
this.http = http;
}
activate() {
this.http.fetch('browsequotes/v1.0/GB/GBP/en-GB/UK/anywhere/anytime/anytime?apiKey=MYAPIKEYGOESHERE')
.then(response => {
console.log(response);
console.log(response.response);
console.log(response.content);
console.log(response.data);
})
.catch(ex => {
console.log(ex);
});
}
}
But when the response object is printed it has NOTHING in it:
Response {}
body: null
bodyUsed: false
headers: Headers
__proto__: Headers
ok: false
status: 0
statusText: ""
type: "opaque"
url: ""
__proto__: Response
All of the remaining console.log's produce undefined
Am I using fetch-client incorrectly? What am I missing?
Notice you're receiving an opaque response (type: "opaque"). Opaque responses does not allow you to read them. This is due to the no-cors mode you set before. You should use the cors mode and SkyScanner should provide the proper headers for your API key which is something I think they don't do.
I fixed my issue which can fall under same heading so leaving an answer here as I couldn't find anything on the net. May be I'm just stupid but i was doing this before...
.then(response => {response.json()})
.then(data => console.log(data))
Banged my head against this for a day and turned out the fix is:
.then(response => response.json())
.then(data => console.log(data))
Or
.then(response => { return response.json()})
.then(data => console.log(data))
Simple really and nothing to do with Aurelia or Fetch but understanding of Javascript syntax.