Title:
Uncaught ReferenceError and CORS Policy Issue in XMLHttpRequest
Description:
I’m facing two issues in my web application:
Uncaught ReferenceError:
When clicking a button, I’m encountering “Uncaught ReferenceError: accessData is not defined,” although the function is declared in my JavaScript code.
CORS Policy Error:
I’m making an XMLHttpRequest to ‘http://localhost:8000/backend’ from my front-end code.
The request is blocked due to a CORS policy issue: “Access to XMLHttpRequest at ‘http://localhost:8000/backend’ from origin ‘null’ 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.”
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors'); // Add this line
const app = express();
const port = 8000;
app.use(cors()); // Enable CORS
app.use(bodyParser.json());
// Function to check if it's lunch break
function accessDataDuringLunchBreak() {
const currentHour = new Date().getHours();
return currentHour >= 12 && currentHour < 13;
}
app.post('/backend', (req, res) => {
const action = req.body.action;
if (action === 'delete_data') {
if (accessDataDuringLunchBreak()) {
res.status(403).json({ error: 'Access denied during lunch break' });
} else {
// Implement your logic to delete data here
res.json({ message: 'Data deleted successfully' });
}
} else {
res.status(400).send('Invalid action');
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Access and Deletion</title>
</head>
<body>
<button onclick="accessData()">Access Data</button><br><br>
<button onclick="deleteData()">Delete Data</button>
<script>
function accessData() {
if (accessDataDuringLunchBreak()) {
alert("Access denied during lunch break!");
} else {
// Perform AJAX request for data access (you can implement this as needed)
alert("Data accessed successfully!");
}
}
function deleteData() {
if (accessDataDuringLunchBreak()) {
alert("Access denied during lunch break!");
} else {
// Perform AJAX request for data deletion
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.message);
} else {
var error = JSON.parse(xhr.responseText);
alert(error.error);
}
}
};
xhr.open("POST", "http://localhost:8000/backend", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ action: 'delete_data' }));
}
}
function accessDataDuringLunchBreak() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
// Assuming lunch break is between 12:00 PM and 1:00 PM
return (currentHour >= 12 && currentHour < 13);
}
</script>
</body>
</html>