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
From what I see, you
index.html
and youservidor.js
are not connected in any way. That is to say, your server is not, literally, serving it ,index.html
so it does not understand it as its own, therefore it blocks the request.There are several ways to resolve this issue:
index.html
ie, that file can only be accessed through the server.header
:Access-Control-Allow-Origin
in the response.Solution one.
You will have to serve
index.html
fromservidor.js
:Now you must visit
http://localhost:5555/
and when you open the console you will see that yourjugadores
are being brought from the database.Why does it work?
Because the server understands that the request is originating from the same origin , that is,
http://localhost:5555
.Solution two.
Add the
header
:Access-Control-Allow-Origin
manually:Solution three.
Add
cors
to your server.Why does it work?
The method
.use()
executes middleware (a middleware is simply a function that can modify therequest
andresponse
of a request before that request is executed on the desired route). In this case, the middleware we are using iscors()
that it modifies theresponse
server object that allows access to the server via theheader
:Access-Control-Allow-Origin
.These are some readings that might interest you to understand more about the subject: