How to return json from fetch construct?

  • 0
    Hello everyone, tell me how you can return json from the fetch construction. To call it anywhere and work with a json file.

    function translate(){
    fetch('https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&hl=ru&dt=t&dt=bd&dj=1&source=icon&tk=467103.467103&q=привет', {
      method: 'get',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      },
      //body: JSON.stringify({a: 7, str: 'Some string: &=&'})
    }).then(res=>res.json())
      .then(res => console.log(res));
    }
    console.log(translate())


    Gives an error message. Can't get json from this function
    JavaScript Anonymous, Oct 2, 2019

  • 4 Answers
  • 0
    Your code is correct. The request does not work for the reason described in the error you are receiving.

    Details: google "fetch has been blocked by cors policy"
    Anonymous

  • 0
    If there is an error with CORS and the project is on localhost, then try this:

    1) Work on a project through firefox, it has a weaker attitude to cors policy than chrome.

    2) install the cors everywhere extension, activate the plugin on the project page and reload the page with the project.

    3) pass your request through the proxy:

    An example on React did (don't pay attention to the ZhZ method)

    componentDidMount() {
    const proxyurl = "https://cors-anywhere.herokuapp.com/"; //Прокси как ты понял
    const url = "https://jsonplaceholder.typicode.com/users"; // твой сайт который не отправляет CORS
    fetch(proxyurl + url)
    .then(response => response.json())
    .then(users => { this.setState({ state: users }) })
    .catch(() => console.log("Can’t access " + url + " ERROR!!!"))
    }
    Anonymous

  • 0
    fetch('https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&hl=ru&dt=t&dt=bd&dj=1&source=icon&tk=467103.467103&q=привет', {
    method: 'POST',
    }).then(res=>res.json())
    .then(function(res){
    console.log(res);
    console.log(res['sentences']);
    //делаем что-то с данными.....
    });
    Anonymous

  • 0
    Something like this:

    async function translate() {
    var response = await fetch('https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&hl=ru&dt=t&dt=bd&dj=1&source=icon&tk=467103.467103&q=привет');
    var obj = await response.json();
    return obj;
    }

    console.log(await translate());


    It is always better to use async / await instead of promises, since they are an order of magnitude shorter code.

    And yes, I have no errors, everything works.
    Colin Spencer

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!