当我使用JavaScript连接到我的REST API时,出现跨域网络错误。

huangapple go评论88阅读模式
英文:

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

问题

如果我执行curl localhost:8080/recipes,它可以工作。但是如果我在Firefox的JavaScript代码中使用我的代码,会出现以下错误:

  • 跨域请求被阻止:同源策略禁止读取https://localhost:8080/recipes的远程资源。(原因:CORS请求未成功)。状态码:(null)。
  • TypeError:尝试获取资源时出现网络错误。

然而,如果直接使用URL,它可以工作:

我的JavaScript客户端代码非常简单:

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);

}

提前感谢。

英文:

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.

当我使用JavaScript连接到我的REST API时,出现跨域网络错误。

However if use directly the url it works:

当我使用JavaScript连接到我的REST API时,出现跨域网络错误。

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.

答案1

得分: 3

要解决这个问题,你可以在客户端使用代理,或者在服务器端启用CORS。默认情况下,CORS禁止在两个不同端口之间进行请求。

英文:

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

答案2

得分: 3

你正在尝试使用"https"连接到本地主机,这导致你的请求出现了跨域错误。

在你的请求URL中,使用的是"http"。所以请修改这一行代码:

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

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

答案3

得分: 1

我自己修复了,很简单:

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

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

使用 cors 包,我需要添加下面这行代码:
router.Use(cors.Default())
谢谢!

英文:

I fixed by myself it is easy:

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

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

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

huangapple
  • 本文由 发表于 2022年1月3日 15:19:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/70562675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定