i am very very new to backend and express js. I wanted to fetch data from my rest api but it is sending this error net::ERR_FAILED.
//my api
const express = require("express");
const app = express();
app.get("/", (req, res)=>{
res.send("hello world!!!")
})
const videos = {
"source": "....com",
"url": "...com"
}
app.get("/api/home", (req, res)=>{
res.send(videos)
})
app.listen(3500, ()=>console.log("listening at port 3500..."))
<!DOCTYPE html>
<html>
<head>
<title>Hey</title>
</head>
<body>
<button onclick="init()">hey</button>
<script>
function init(){
const url = "http://localhost:3500/api/home"
fetch(url).then(res=>res.json()).then(result=>{
console.log(result)
})
}
</script>
</body>
</html>
I want to console log the data videos
from the api when i click the button, but its not working.
it even says:
Access to fetch at 'http://localhost:3500/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. index.html:12 GET http://localhost
Because your front-end service address port and back-end service address port are different, Cross-Origin Resource Sharing is triggered. That's why you got the error in the console of the browser.
In order to enable CORS, we can use cors middleware.
Or, use a http-proxy-middleware to proxy your API to the target server.
Frontend => local HTTP server => target server.