I'm learning node.js and I made a server that receives a get request, but is blocked by Cors policy. I am working with express and axios. I greatly appreciate your help.
I add my code below:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const puerto = 5555
document.addEventListener('DOMContentLoaded', getData)
async function getData() {
let res = await axios.get(`http://localhost:${puerto}/jugadores`)
json = await res.data;
console.log(json)
}
</script>
</body>
</html>
servidor.js
const express = require('express')
const { jugadores } = require('./base-datos')
const app = express()
app.get('/jugadores',(req, res)=>{
res.send(jugadores)
})
puerto = 5555
app.listen(puerto, () => {
console.log(`Puerto ${puerto}. Escuchando ...`)
});
base-datos.js
let jugadores = [
{
"id": 1,
"nombre": "Jugador1"
},
{
"id": 2,
"nombre": "Jugador2"
}
]
module.exports.jugadores = jugadores
And these are the errors that I get in the console:
Access to XMLHttpRequest at 'http://localhost:5555/jugadores' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
Uncaught (in promise) ocode: "ERR_NETWORK"config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}message: "Network Error"name : "AxiosError"request: XMLHttpRequest {data: undefined, onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, …}response: XMLHttpRequest {data: undefined, onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, …}[[Prototype]]: Error