How can I display images with cors problems and without server access - api

I'm fetching data (I'm working with ReactJS) from an API's endpoint. Cors is enable.
My problem is, when I'm trying to display images (with or ), Cors is blocking access to images.
I tried to add crossOrigin='anonymous' to but it didn't work.
I do not have any access to the server.
I can fetch and display all the other datas.
I'm a little bit despaired, so if you have any idea to help me to display my images, it will be so great !!! :)
How I fetch my datas :
fetch(myURL)
.then(response => response.json())
.then(data => this.setState({ items: data.items }))
.catch(error => {
console.log(error);
this.setState({
error: true
});
});

You can either use a Proxy Server or Disable Same Origin Policy in your browser.
Here's a detailed tutorial :
https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/

Related

GET Request fails in Vuejs Fetch but works perfectly in Postman and in browser due to 302 redirection

I have a web application built using NuxtJS/Vuejs within that I have a field where user can provide the URL and my application should make a GET request to that URL and obtain the data. Mostly the URL is related to GitHub from where it should fetch XML/JSON the data.
When I provide a certainly URL in browser/Postman then the redirection happens and data from the redirected URL is loaded. I want to achieve the same in my code but it's not happening and I get the error:
index.js:52 GET {{URL}} net::ERR_FAILED 302
But these URL works perfectly in browser and in Postman without any issue. Following is my code where I am making the request using Vuejs Fetch:
fetch(inputURL, {
method: 'GET'
})
.then((response) => {
console.log('RESPONSE')
console.log(response)
})
.catch((error) => {
console.log('ERROR')
console.log(error.response)
})
Using the Axios:
axios
.get(inputURL)
.then((response) => {
console.log("RESPONSE");
console.log(response);
})
.catch((error) => {
console.log("ERROR");
console.log(error);
})
I tried setting various header, I tried using axios etc but nothing seems to work for me. Can someone please explain to me what am I doing wrong and how to fix this issue? Any help or workaround would be really appreciated.
First of all, the 'Access-Control-Allow-Origin' header is something that should be set up on the server side, not on the client making the call. This header will come from the server to tell the browser to accept that response.
The reason why your code works from postman/browser is because you're not under the CORS rules when you request it like that.
One way around it, would be to make a call to your backend and tell the backend to call GET the data from the URL provided and then return it to your front-end.
Example:
//call_url.php
<?php
$url = $_GET['url'];
$response = file_get_contents($url);
echo $response
?>
//vue.js component
<input type="text" v-model="url"></input>
<button type="button" #click="callUrl">call me</button>
...
methods: {
callUrl() {
axios.get('call_url.php?url=' + encodeURIComponent(this.url))
.then(response => {
//...do something
}
}
}
As mentioned in another answer it's not possible for any library including Fetch and Axios to make requests and obtain the Data due to various security policies. Hence, I created a method in my Spring boot application that will obtain the data from URL and I make a request to my Spring boot using Axios.
import axios from 'axios'
axios.post('/urlDataReader', inputURL)
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Spring boot app:
//Method to read the data from user-provided URL
#PostMapping(value = "/urlDataReader", produces = "text/plain")
public String urlDataReader(#RequestBody String inputURL) {
final String result = new RestTemplate().getForObject(inputURL, String.class);
return result;
}

Nuxtjs/Vuejs with axios trying to access URL results in Access to XMLHttpRequest at has been blocked by CORS policy

I am aware there are many answers related to this question but since nothing seems to work I am posting here.
I have NuxtJS/Vuejs application within which users can provide the GitHub URL (mostly the URL will contain the XML/JSON files). After getting the URL, I want to make a request to the URL using the axios and obtain the data present within the URL.
When I try to make a request i get the following error:
Access to XMLHttpRequest at 'GitHub URL' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'Some GITHUB URL', but only one is allowed.
When I provide the same URL in the browser then I get the 302 status and obtain the raw JSON/XML data after redirection. I want to implement the same in my code.
If data is not found in the URL then obtain the redirection URL from the response and make another request with the new URL. But due to the CORS error and other error GET GIT HUB URL net::ERR_FAILED I am unable to get the response.
I tried many things mentioned on the website such as:
Adding proxy as mentioned here: https://stackoverflow.com/a/55481649/7584240
Adding a prefix to URL as mentioned here: https://stackoverflow.com/a/56781665/7584240
Adding the condition to axios as mentioned here: https://stackoverflow.com/a/48293817/7584240
And many other things but nothing seems to work for me and getting the same error. Can someone please help me with this issue?
Following is the sample code I have (The code is part of VUEX Store actions):
export const actions = {
obtainURLData ({ commit, state, dispatch, rootState }, inputURL) {
axios
.get(inputURL)
.then((response) => {
console.log('INSIDE RESPONSE')
console.log(response)
console.log(response.data)
if (response.status === 200) {
}
})
.catch((error) => {
console.log('INSIDE ERROR')
console.log(error)
console.log(error.response)
console.log(error.response.data.detail)
console.log(error.response.status)
})
}
}

How to retrieve cookies in express via browser?

I've been trying to figure this out for 2 days now, but to no avail. I'm using cookie-parser and have followed the code of other people but it's still not working. It works perfectly in postman, but not on the browser. The browser I'm currently using is google chrome, but I've also tested it on microsoft edge which gives the same result.
app.get('/testCookie',(req,res) => {
res.cookie('username','flavio');
res.json({message:req.cookies});
})
// frontend
const data = await axios.get('http://localhost:5000/testCookie');
console.log(data); // returns {}
Asper, I understand you want to set cookies and access it in the client-side, then this might help you.
Server-side
const cookieConfig = {
httpOnly: false,
maxAge: 315569260000,//age of cookie any value possible
}
app.get('/testCookie',(req,res) => {
res.cookie('username','flavio',cookieConfig);
})
Client side
let data = document.cookie
.split('; ')
.find(row => row.startsWith('username'))
.split('=')[1];
console.log(data)

Access Dyson server from React Native ios

I'm using Dyson to host a little mock server for my React Native app, and trying to fetch from the server. The server appears to be running well and when I visit my desired url, http://localhost:3000/stations, in my browser, I get a nice JSON response.
In my React Native action, though, I get Network request failed:
export function fetchStations() {
return dispatch => {
dispatch({ type: "GET_STATIONS_START" });
fetch("http://localhost:3000/stations")
.then(res => {
return res.json();
})
.then(json => {
dispatch({ type: "GET_STATIONS_SUCCESS", payload: json.stations });
})
.catch(error => {
console.warn(error);
dispatch({ type: "GET_STATIONS_FAILURE", payload: error });
});
};
}
Using a static local URL works, and using, say, the Google Maps API works (even though it's not what I want, it's just a sample API to try).
I would think I may be calling the url wrong but it works in the browser so that seems doubtful. My guess is that is has something to do with iOS not liking http requests (only accepting https), unless you set some setting somewhere (I've been through this in native iOS development).
If this is the problem, how do I fix it from React Native? Or, what is the actual problem?
PS. I'm using dyson rather than json-server because for some reason I can't get json-server to work. See my other post. Somewhere here :)
I figured it out. The device (simulator) doesn't have access to localhost so I had to set my url to http://127.0.0.1:3000/stations and it works like a dream.

React-native Fetch GET, while passing request items to the url

I have a Django-REST API that I am trying to access with a React-native app. I would like to achieve the same result that the command line
http GET http://mywebsite.com/api param1=value1 param2=value2
but using the fetch() function from the networking tutorial. How can I specify the request items to the fetch while using the GET method?
EDIT: my goal is to able to perform a token authentication to a django rest API which need these request item for the page to be accessed.
fetch() uses the exact URL string you provide to perform the request.
Include URL params in your url like when you are calling fetch()
fetch("http://whatever.xyz?param1=1&param2=2")
The simplest way to handle this is by using something similar to the following function
function apiCall() {
return fetch('http://mywebsite.com/api/?param1=value1&param2=value2')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}