Description:
I am trying to send JSON data from an HTML page to the Node.js server running locally on port 5000 using Fetch API.
Getting Error:
Access to fetch at 'http://localhost:5000/attend' from origin 'http://127.0.0.1:5501' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
port error:
POST http://localhost:5000/attend net::ERR_FAILED
Fetch error:
Uncaught (in promise) TypeError: Failed to fetch
Node.js Code:
connectdb();
const app = express();
app.use(express.static('public'));
app.use(express.json({extended: false}));
app.use (bodyParser.json());
app.get('/',(req,res)=> res.send('API RUNNING'));
app.post('/attend',async (req,res)=>{
const {name,rollnumber} = req.body;
console.log(name);
console.log(rollnumber);
try {
let data = await Database.findOne({ rollnumber });
if (data) {
return res
.status(400)
.json({ errors: [{ msg: 'attandence is marked all ready' }] });
}
const Data = new Database({
rollnumber,
name
});
await Data.save();
res.json("added success fully");
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Marked</title>
<link rel="stylesheet" href="/Client/style.css">
<script>
function attend(){
const data = {
name:'Syed Ali Shahzil',
rollnumber:'180996'
};
const options = {
method:'POST',
headers:{
'Content-Type' : 'application/json;charset=UTF-8'
},
body: JSON.stringify(data)
};
fetch('http://localhost:5000/attend',options);
}
</script>
</head>
<body>
<div>
<ul>
<li><a href="/">Home</a></li>
<li><a class="active" href="marked.html">attendence Marked</a></li>
</ul>
<button class="button" onclick="attend()"> Present</button>
</div>
</body>
</html>
http://127.0.0.1:5501) does not match your destination domain (http://localhost:5000). Yes,127.0.0.1andlocalhostare synonymous, but even a difference in port number will trigger the error. See: Same Origin Policy