I don't know why but I got confused regarding Nodejs one behaviour.
Following is my nodejs code my server is running at port:8080
const express = require("express");
const app = express();
const multer = require("multer");
const cors = require('cors');
app.use(cors({
origin:"http://localhost:4000"
}))
app.get("/userinfo", async (req, res) => {
console.log("reached heree");
res.json({
message: "access",
});
});
app.listen(
8080,
(error) => {
if (error) {
console.log("error");
}
},
() => {
console.log("listening at port 8080");
}
);
And I am trying to hit API from a different origin [localhost:3000]
import logo from './logo.svg';
import './App.css';
import axios from "axios";
function App() {
const makeRequest =()=>{
axios.get("http://localhost:8080/userinfo").then(response=>{
console.log(response);
}).catch((e)=>{
console.log(e);
})
}
return (
<div className="App">
<button onClick={makeRequest}>Click</button>
</div>
);
}
export default App;
But when I click Click when I inspect the code, I got an error message as expected You are blocked by CORS policy.But when I see in terminal on my server-side, I see output Reached here.
At this point, I got too confused and frustrated at the same time. How cross-site request triggered /userinfo from the different origin?. I don't think this should happen.
How can I solve this issue??
It's not your server that is blocking the request. Your server SHOULD send back the HTTP request because servers and WIFI and your router does not care about CORS.
It is the web browser that blocks the CORS. Blocking CORS does not mean you don't hit the server endpoint. It does not even mean that the HTTP packet is blocked. Blocking CORS means your web browser is refusing to let your javascript code from reading the data returned by the server.
The purpose of CORS is to bypass the original Same-origin policy which is still enforced today. The same-origin policy was added when javascript was added to web browsers. It allows web browsers to make HTTP requests but tries to prevent malicious scripts from listening in to HTTP data by disallowing scripts to read the result of HTTP requests (XMLHttpRequest or fetch) unless the URL is from the same domain as the page.
The only thing CORS adds is a header that your server can send back to the browser that tells the browser that it's OK for javascript code to access the result of the HTTP request.