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('привет', {
      method: 'get',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      //body: JSON.stringify({a: 7, str: 'Some string: &=&'})
      .then(res => console.log(res));

    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"

  • 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 = ""; //Прокси как ты понял
    const url = ""; // твой сайт который не отправляет CORS
    fetch(proxyurl + url)
    .then(response => response.json())
    .then(users => { this.setState({ state: users }) })
    .catch(() => console.log("Can’t access " + url + " ERROR!!!"))

  • 0
    fetch('привет', {
    method: 'POST',
    //делаем что-то с данными.....

  • 0
    Something like this:

    async function translate() {
    var response = await fetch('привет');
    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!