2

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.com/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");
    });
  }
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. Commented Jul 10, 2018 at 10:38
  • what does the function fetch do? Commented Jul 10, 2018 at 12:21

2 Answers 2

3

Problem 1

Your URL is wrong.

var url = 'api.apixu.com...

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.com'

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/';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.