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

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

Related

Axios Get Authorization Not Working In Vue But Worked on POSTMAN (Post method on vue worked)

I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?
getCurrentPeriode() {
return new Promise((resolve, reject) => {
axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
headers:{
'Authorization': `Basic ${token}`
}
})
.then((response) => {
resolve(response.data[0])
}) .catch(err => {
reject(err.response.data)
})
})
}
The token:
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}
In postman (it's worked):
I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)
Post method is working like normal, here's the code:
postNewPeriode(date) {
return new Promise((resolve, reject) => {
const data = new FormData()
data.append("dateStart", date.dateStart)
data.append("dateEnd", date.dateEnd)
data.append("X-API-KEY",API_KEY)
axios.post(TABLE_NAME,data, {
headers:{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`
}
})
.then((response) => {
resolve(response)
}) .catch(err => {
reject(err.response.data)
})
})
},
Am I missing something in my axios get or I should use different approach? Thanks for the answer
For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did.
Try using the headers as the second argument on GET.
This should work:
axios.get( TABLE_NAME,
{
headers:{'Authorization': `Basic ${token}`},
params: {"X-API-KEY": API_KEY, command:"getCurrent"}
}
)

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));

Express CORS response

I am using express to return an api response retrieved via a request call.
router.post('/', function(req, res){
var options = {
...
}
rp(options)
.then(function (parsedBody) {
console.log(parsedBody);
res.json(parsedBody)
})
The console log displays the expected payload, also when I use Postman I also see the expected payload.
When though my client app gets the response it is:
Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}
Ive tried adding CORS middleware:
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Rquested-With, Content-Type, Accept");
next();
});
My client is a very simple react app using fetch:
fetch('http://localhost:3001/api/', {
method: 'POST',
dataType: 'JSON',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
}).then((response) => {
console.log(response);
}).catch((response) => {
console.log('Error');
});
My react app is localhost:3000 and the express api localhost:3001, the expected payload is a very simple object...
{
athlete: {
firstname: "Matt"
...
}
}
How can I just forward on the api request response to the clients fetch success method?
The problem is not CORS related, the response within the react app needed parsing as json:
.then((response) => {
console.log(response.json());
})

Fetch with devise_token_auth in react-native

I'm new with react-native. I'm trying to satisfy the devise_token_auth requirement of send in every request the authetication headers. To do so, I'm trying something like this:
export const scheduleFetch = (auth) => {
return (dispatch) => {
fetch(URL, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'access-token': auth['acessToken'],
'token-type': auth['tokenType'],
'client': auth['client'],
'uid': auth['uid']
}
})
.then((response) => {
console.log(response)
response.json()
})
.catch((error) => console.log(error))
}
}
My back-end is receiving the request, all headers are fill. However, I still receiving the message "_bodyText":"{\"errors\":[\"You need to sign in or sign up before continuing.\"]}".
How can I make that work? Am I jumping any step?

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.