最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

go - when I connect with javascript to my REST API: cross-origin network error - Stack Overflow

programmeradmin5浏览0评论

if I execute curl localhost:8080/recipes it works. But if I use my code in javascript in firefox appears the following errors:

  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8080/recipes. (Reason: CORS request did not succeed). Status code: (null).
  • TypeError: NetworkError when attempting to fetch resource.

However if use directly the url it works:

My client code in javascript is very simple:

const url = 'http://localhost:8080';

const ul = document.getElementById('parrafo');
const list = document.createDocumentFragment();

const btn = document.getElementById("boton");

btn.addEventListener("click", function () {

  sendData();

});


function sendData(){

fetch(url + "/recipes")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    let recipes = data;

    recipes.map(function(recipe) {
      let li = document.createElement('li');
      let name = document.createElement('h2');
      let id = document.createElement('span');

      name.innerHTML = `${recipe.name}`;
      id.innerHTML = `${recipe.id}`;

      li.appendChild(name);
      li.appendChild(id);
      list.appendChild(li);

      
    });
  })
  .catch(function(error) {
    console.log(error);
  });

  ul.appendChild(list);

}

Thanks in advance

====================================

In the same machine, in developer environment, How should the frontend be executed, directly in a browser? (Do i open it directly with firefox?) With the backend I have no problem at all, it is working perfectly.

if I execute curl localhost:8080/recipes it works. But if I use my code in javascript in firefox appears the following errors:

  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8080/recipes. (Reason: CORS request did not succeed). Status code: (null).
  • TypeError: NetworkError when attempting to fetch resource.

However if use directly the url it works:

My client code in javascript is very simple:

const url = 'http://localhost:8080';

const ul = document.getElementById('parrafo');
const list = document.createDocumentFragment();

const btn = document.getElementById("boton");

btn.addEventListener("click", function () {

  sendData();

});


function sendData(){

fetch(url + "/recipes")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    let recipes = data;

    recipes.map(function(recipe) {
      let li = document.createElement('li');
      let name = document.createElement('h2');
      let id = document.createElement('span');

      name.innerHTML = `${recipe.name}`;
      id.innerHTML = `${recipe.id}`;

      li.appendChild(name);
      li.appendChild(id);
      list.appendChild(li);

      
    });
  })
  .catch(function(error) {
    console.log(error);
  });

  ul.appendChild(list);

}

Thanks in advance

====================================

In the same machine, in developer environment, How should the frontend be executed, directly in a browser? (Do i open it directly with firefox?) With the backend I have no problem at all, it is working perfectly.

Share Improve this question edited Jan 3, 2022 at 16:08 grafeno30 asked Jan 3, 2022 at 7:19 grafeno30grafeno30 5291 gold badge7 silver badges19 bronze badges 3
  • The problem is related to the backend. which package do you use for the webserver? gin? – Amirreza Noori Commented Jan 3, 2022 at 7:25
  • Hey, so for security reasons, browsers block requests from and to different ports on the same system. To fix this, you have to enable CORS by adding headers for access-control-allow-origin in your frontend and some related specification to your backend as well. lots of examples available on the net. – Sampurna Commented Jan 3, 2022 at 7:31
  • Does this answer your question? No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API – voiarn Commented Jan 3, 2022 at 7:33
Add a ment  | 

3 Answers 3

Reset to default 4

You are trying to connect to localhost with "https", which makes your request cors error.

in the URL your request is with "HTTP". so change this line :

const url = 'http://localhost:8080';

Either you must to use a proxy on the client side or enable CORS on the server side. By default, requests between two different ports are disabled by CORS

I fixed by myself it is easy:

import (
    "encoding/json"
    "io/ioutil"
    "net/http"
    "time"

    "github./gin-contrib/cors"
    "github./gin-gonic/gin"
)

Using the package cors I have to add the next line: ** router.Use(cors.Default()) ** Thanks!!

发布评论

评论列表(0)

  1. 暂无评论