Reputation: 61
I am trying to make an API call to a remote server, Initially, I got this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I temporarily solve this error by attaching the https://cors-anywhere.herokuapp.com
link before the link, or sometimes using the Moesif Cors-Any-where Chrome extension. The fetch now returns 200 ok status
but the response is empty.
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
response: {}
data: undefined
However, if I run the same query on postman, it returns the expected response JSON object. How do I fix this?
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then(response => {
if (response.ok) {
console.log(response)
return response
}
else
console.log(`Looks like something went wrong. Status: ${response.status}`)
})
.then(response => {
response.json()
console.log("response: " + JSON.stringify(response))
})
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
Upvotes: 1
Views: 11051
Reputation: 3714
I know this is a very old question, but I've got exact same problem last night. The issue was the SSL connection, which is enforced by Chrome and is not enforced by Postman. So just make sure your API can handle https
protocol.
Upvotes: 0
Reputation: 379
Add A Header For accept all as follow in the front-end request
Upvotes: 1
Reputation: 1036
response.json()
returns a promise, you have to wait for resolving this. you also have to return something if you want the next then
in the chain to receive something.
something like this should work:
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then((response) => {
if (response.ok) {
return response
} else {
throw `Looks like something went wrong. Status: ${response.status}`;
}
})
.then(response => response.json())
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
or with your console.log:
return response.json().then((data) => console.log(data));
Upvotes: 1
Reputation: 1036
if you want to request data from a server it has to be on the same domain, or the 'Access-Control-Allow-Origin' header
has to be set.
I wont rely on a service like https://cors-anywhere.herokuapp.com
For development you can use a proxy server
to bypass this limitation. (many frameworks already have a solution for this, i don't know which one you use)
Upvotes: 0