I am using openweather api to create a weather application but my fetch api call is not working. My api call is working in browser but not in my code.
handleSubmit(){
var city = this.state.city;
var url = 'api.apixu/v1/current.json?key=67deb752d27d411a9ac101935181007&q=' + city;
console.log(url);
fetch(url, {
method: 'GET',
mode: "no-cors",
headers: { 'Content-Type': 'application/json' }
}).then((res) => {
var resJson = JSON.parse(res);
console.log(resJson);
return resJson;
}).then((resJson) => {
}).catch((err) => {
console.log("error");
});
}
I am using openweather api to create a weather application but my fetch api call is not working. My api call is working in browser but not in my code.
handleSubmit(){
var city = this.state.city;
var url = 'api.apixu./v1/current.json?key=67deb752d27d411a9ac101935181007&q=' + city;
console.log(url);
fetch(url, {
method: 'GET',
mode: "no-cors",
headers: { 'Content-Type': 'application/json' }
}).then((res) => {
var resJson = JSON.parse(res);
console.log(resJson);
return resJson;
}).then((resJson) => {
}).catch((err) => {
console.log("error");
});
}
Share
Improve this question
edited Jul 10, 2018 at 13:10
imixtron
3031 silver badge10 bronze badges
asked Jul 10, 2018 at 10:35
Shashank LohaniShashank Lohani
791 gold badge2 silver badges5 bronze badges
2
-
You are making a GET request. There is no content in the request to describe the type of.
headers: { 'Content-Type': 'application/json' }
is utter nonsense (and is actively harmful as it makes the request require a preflight OPTIONS request). Remove it. – Quentin Commented Jul 10, 2018 at 10:38 -
what does the function
fetch
do? – imixtron Commented Jul 10, 2018 at 12:21
2 Answers
Reset to default 3Problem 1
Your URL is wrong.
var url = 'api.apixu....
You forgot the scheme (https://
or something should be at the front of that).
Problem 2
You said mode: "no-cors"
which means:
I want to make this HTTP request, but I am not going to do anything that requires permission, so don't ask for permission, don't do anything that needs permission, and don't throw errors if I don't get permission
Reading data from a different origin requires permission. Since you said you didn't want permission, you can't read the data and it fails silently.
Remove mode: "no-cors"
. Use mode: "cors"
instead.
I had the same issue and the only thing that worked for me was to send my request to a proxy server.
This redirect did not work too:
const baseUrl = 'https://cors-anywhere.herokuapp.'
After troubleshooting this issue for a long time, I redirected the response to another website and finally works.
const App = () => {
....
const baseUrl = 'https://thingproxy.freeboard.io/fetch/';