0

I am trying to create a simple AJAX request to AccuWeather but the JSON method won't convert the returned data to a JS object.

All I get is:

Status_code: "JSON_VALIDATION",
status_msg: "Syntax error. Incorrect input JSON. Please, check fields with JSON input."*

What I do wrong?

async function getWeather() {
  try {
    const request = await fetch(
      'https://accuweatherstefan-skliarovv1.p.rapidapi.com/searchByLocationKey', {
        'method': 'post',
        'headers': {
          'x-rapidapi-host': 'AccuWeatherstefan-skliarovV1.p.rapidapi.com',
          'x-rapidapi-key': '...',
          'content-type': 'application/x-www-form-urlencoded'
        },
        'body': {
          'locationkey': 'IL',
          'apiKey': 'xxxxx'
        }
      }
    );
    const data = await request.json();
    return data;
  } catch (error) {
    alert(error);
  }
}
getWeather();
getWeather('IL').then(resolved => {
  console.log(resolved);
});
2
  • what do you get when you console.log(request) just after the fetch call and before calling .json? Commented Feb 8, 2020 at 19:37
  • I get the AJAX response in the JSON format (Readable stream) @Addis Commented Feb 8, 2020 at 20:27

1 Answer 1

1

The problem is not with the conversion of the json response, but with sending the request. You can't send an object in body, you should send a JSON string, or in your case, create a formdata object:

const formData = new FormData();
formData.append('locationkey', 'IL');
formData.append('apiKey', 'apiKey');

and pass it as body:

const request = await fetch(
    'https://accuweatherstefan-skliarovv1.p.rapidapi.com/searchByLocationKey',
    {
        'method': 'post',
        'headers': {
            'x-rapidapi-host': 'AccuWeatherstefan-skliarovV1.p.rapidapi.com',
            'x-rapidapi-key': '...',
            'content-type': 'application/x-www-form-urlencoded'
        },
        'body': formData
    }
);
Sign up to request clarification or add additional context in comments.

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.