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

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

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客户端代码非常简单:

  1. const url = 'http://localhost:8080';
  2. const ul = document.getElementById('parrafo');
  3. const list = document.createDocumentFragment();
  4. const btn = document.getElementById("boton");
  5. btn.addEventListener("click", function () {
  6. sendData();
  7. });
  8. function sendData(){
  9. fetch(url + "/recipes")
  10. .then((response) => {
  11. return response.json();
  12. })
  13. .then((data) => {
  14. let recipes = data;
  15. recipes.map(function(recipe) {
  16. let li = document.createElement('li');
  17. let name = document.createElement('h2');
  18. let id = document.createElement('span');
  19. name.innerHTML = `${recipe.name}`;
  20. id.innerHTML = `${recipe.id}`;
  21. li.appendChild(name);
  22. li.appendChild(id);
  23. list.appendChild(li);
  24. });
  25. })
  26. .catch(function(error) {
  27. console.log(error);
  28. });
  29. ul.appendChild(list);
  30. }

提前感谢。

英文:

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:

  1. const url = 'http://localhost:8080';
  2. const ul = document.getElementById('parrafo');
  3. const list = document.createDocumentFragment();
  4. const btn = document.getElementById("boton");
  5. btn.addEventListener("click", function () {
  6. sendData();
  7. });
  8. function sendData(){
  9. fetch(url + "/recipes")
  10. .then((response) => {
  11. return response.json();
  12. })
  13. .then((data) => {
  14. let recipes = data;
  15. recipes.map(function(recipe) {
  16. let li = document.createElement('li');
  17. let name = document.createElement('h2');
  18. let id = document.createElement('span');
  19. name.innerHTML = `${recipe.name}`;
  20. id.innerHTML = `${recipe.id}`;
  21. li.appendChild(name);
  22. li.appendChild(id);
  23. list.appendChild(li);
  24. });
  25. })
  26. .catch(function(error) {
  27. console.log(error);
  28. });
  29. ul.appendChild(list);
  30. }

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"。所以请修改这一行代码:

  1. 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 :

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

答案3

得分: 1

我自己修复了,很简单:

  1. import (
  2. "encoding/json"
  3. "io/ioutil"
  4. "net/http"
  5. "time"
  6. "github.com/gin-contrib/cors"
  7. "github.com/gin-gonic/gin"
  8. )

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

英文:

I fixed by myself it is easy:

  1. import (
  2. "encoding/json"
  3. "io/ioutil"
  4. "net/http"
  5. "time"
  6. "github.com/gin-contrib/cors"
  7. "github.com/gin-gonic/gin"
  8. )

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:

确定