if I execute curl localhost:8080/recipes it works. But if I use my code in javascript in firefox appears the following errors:
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.
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.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!!