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

This question already has an answer here:
Axios having CORS issue
2 answers
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

Related

getting data with fetch is working but not with axios

I can get my data with fetch
let myHeaders = new Headers();
myHeaders.append('X-Auth-Token', token,);
myHeaders.append('Content-Type', 'application/json');
fetch("myUrl", {
withCredentials: true,
headers: myHeaders
}).then(function (response) {
console.log(response)
})
but fetching data is not working with axios. this is my axios code
const headers={
'X-Auth-Token': token,
"content-type":"application/json"
}
axios.get('myUrl',{headers:headers,withCredentials:true})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
});
I use it this way:
Check if your headers object is in good shape with a console log.
const headers = {
'X-Auth-Token': token,
'content-type': 'application/json'
};
console.log(headers);
const request = axios.create({
myUrl,
headers: myHeaders,
withCredentials: true
})
request.get() // If you add a string inside the brackets it gets appended to your url
.then(res => console.log(res))
.catch(err => console.log(err))
If the error you are getting is about CORS (Cross Origin Resource Sharing):
If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol, domain, port.
You need to set the server to allow your origin.
It's a very common problem and you will see it happen often. Read more about cors here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

How allow my app to POST a cloudfunction in firebase that makes another POST?

I'm trying a react app that consumes firebase functions, here my code:
handleDonate(key){
const url = 'https://us-central1-bora-ajudar-73ebc.cloudfunctions.net/api/donate'
const dados = {teste : 'oi'}
const options = {
method: 'POST',
headers: {'Access-Control-Allow-Origin' : '*'},
data : dados,
url
}
axios(options)
.then(data=>{
console.log(data)
})
.catch(err =>{
console.log(err)
})
}
Then, my index.js function
app.use(cors({origin: true}));
admin.initializeApp()
const checkoutUrl = 'https://pagseguro.uol.com.br/v2/checkout/payment.html?code='
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.get('/api', (req,res)=>{
res.send('Server side')
})
app.post('/donate',(req,res)=>{
request({
uri: 'https://ws.pagseguro.uol.com.br/v2/checkout?',
method: 'POST',
form:{
token: token,
email: email,
currency: 'BRL',
itemId1: 'idCampanha',
itemDescription1: 'Doação',
itemQuantity1: '1',
itemAmount1: '2.00'
},
headers:{
'Content-Type': 'application/x-www-urlencode; charset=UTF8',
'Access-Control-Allow-Origin': 'true'
}
})
.then(data=>{
parse(data, (err,json)=>{
res.setHeader('Access-Control-Allow-Origin', 'true')
res.send({
url: checkoutUrl+json.checkout.code[0]
})
})
})
})
When i run it, console shows this error:
Failed to load https://us-central1-bora-ajudar-73ebc.cloudfunctions.net/api/donate: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://bora-ajudar-73ebc.firebaseapp.com' is therefore not allowed access. The response had HTTP status code 500.
I know that is something about sending POST to my function and my function sending another POST, but i dont know exactly what.
The problem is that firebase don't allow external API requests in free plan.

CORS in Express works on Safari but not on Chrome

I have an Express application running on AWS ElasticBeanstalk, for which I have enabled CORS by doing below in my entry point:
app.use(cors());
I can do a simple POST request to an endpoint in my server with Postman or in my React app on Safari, for logging in. I cannot do it on Google Chrome, unfortunately. This is what I get on console:
OPTIONS http://**.eu-central-1.elasticbeanstalk.com/signin 0 ()
On network tab of developer tools, I have this:
I do the API request in React as following:
const customHeader = () => ({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*',
Accept: 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('id_token') || undefined,
});
const base = (method, url, data = {}) => {
return fetch(`${jwtConfig.fetchUrl}${url}`, {
method,
headers: customHeader(),
body: JSON.stringify(data),
})
.then(response => response.json())
.then(res => res)
.catch(error => ({ error: 'Server Error' }));
};
const SuperFetch = {};
['get', 'post', 'put', 'delete'].forEach(method => {
SuperFetch[method] = base.bind(null, method);
});
export default SuperFetch;
And calling:
await SuperFetch.post('signin', userInfo)
The fact that it is working on Postman and Safari leads me to believe that it has something to do with Google Chrome. I also have this extension enabled but it does not solve the problem.
Add this flag as well:
Access-Control-Allow-Headers: Content-Type,Authorization

How to handle CSRF tokens with React Relay

I am busy working on a React Native app which talks to a GraphQL api off a Django server.
In React Native I am using React Relay to try and process my GraphQL requests (following the guide found here) but I am having 403 issues with my requests.
The response says CSRF token missing or incorrect and Im trying to figure out the best way to get this working.
I understand that I need to get a CSRF cookie token first then somehow pass that along with my GraphQL Post request but not having much luck.
My current implementation of this is as follows...
fetch('http://' + ip + ':8000/sign-in/')
.then((response) => {
const cookieHeader = response.headers.map["set-cookie"]; // This gets me a cookie response with a CSRF token
fetch('http://' + ip + ':8000/graphql', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cookie': cookieHeader, // Try and pass the received cookie to my POST
'XSRF-TOKEN': cookieHeader // Trying this as well
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
console.log('RESPONSE', response) // Currently getting a 403
return response.json()
})
})
But this still gets me a 403 error.
I can't seem to find much more information on how to approach this. Can anybody tell where I'm going wrong, or some suggestions on how to otherwise approach this?
(below is a snapshot of my API requests)
So managed to get it working with the following...
return getCsrfToken().then(csrfToken => {
if (csrfToken == null) {
console.log('CSRF NOT SET')
}
const url = 'http://' + ip + '/graphql'
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify({
query: operation.text,
variables,
}),
})
.then(response => {
return response.json()
})
.catch(error => {
console.log('POST ERROR', error)
})
});
function getCsrfToken() {
var url = 'http://' + ip + '/graphql';
return CookieManager.get(url).then(response => {
return response.csrftoken;
});
}
Adding this because this is the most specific question I found for troubleshooting CSRF with Relay for Django + GraphQL
I was getting a similar CSRF error response even though I was posting the CSRF token. I had to add to the fetch headers to match the security settings of my Django backend. In this case I'm Relay in the browser so I get the CSRF token from a cookie.
I had already followed the Django docs for CSRF with AJAX in cookies. Due to my security settings I had to add the "same-origin" credential. I'll label the few things I had to change from the Relay Quick Start tutorial
import { get as getCookie} from 'browser-cookies'
return fetch('/graphql/', { // Added the trailing slash here
method: 'POST',
credentials: "same-origin", // Added this line
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken'), // getting token from cookies
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json();
});
And that's what fixed it for me.

How to make api call to Instagram with axios without CORS error

componentDidMount() {
let token = this.getAccessToken('access_token');
let config = {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Accept: 'application/json'
}
}
if (token) {
axios.get('https://api.instagram.com/v1/users/self/?access_token=' + token, config)
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}
Trying to make an call to Instagram's API but I keep getting this error:
I'm using React.
Any help would be great.
I don't think Instagram supports cross origin requests. They do support jsonp though.
Access-Control-Allow-Origin with instagram api
instagram jquery ajax type="GET, can't get around CORS
You can use a middleman to make your request server-side. There are several to choose from when I search 'no cors npm', but here is an example: https://www.npmjs.com/package/cors

Resources