Pe frontend am un buton, iar când dau click vreau să-mi schimbe o valoare setată în backend.
Deși am făcut setările de CORS în ambele părți, nu mă lasă browserul să fac requestul de POST.
În Firefox îmi zice
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/button_state. (Reason: CORS request did not succeed).
În ‘public/index.html’ este:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Is button clicked?</title>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<button>Change status</button>
<script>
document.querySelector("button").addEventListener("click", () => {
fetch("http://127.0.0.1/button_state", {
method: "POST",
mode: "cors",
headers: {
"Content-type": "application/json charset=UTF-8"
},
body: "buttonState=clicked"
}).catch(err => console.error(`fetch() error: ${err}`));
});
</script>
</body>
</html>
iar în ‘server.js’:
const http = require("http");
const fs = require("fs");
const storage = require("node-persist");
const hostname = "127.0.0.1";
const port = "3000";
(async () => {
await storage.init({ logging: true, ttl: true });
let virtualDB = await storage.getItem("isActive");
if (!virtualDB) {
virtualDB = await storage.setItem("isActive", true);
}
virtualDB = await storage.getItem("isActive");
console.log("virtualDB", virtualDB);
/**
* if the frontend does not work (CORS issues) use curl
* curl -d '{"buttonState":"clicked"}' -H "Content-Type: application/json" -X POST http://localhost:3000/button_state
*
* */
const server = http
.createServer((req, res) => {
if (req.url === "/") {
fs.readFile("./public/index.html", "UTF-8", function(err, html) {
if (err) {
throw err;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html);
});
} else if (req.url === "/button_state" && req.method === "POST") {
let jsonString = "";
req.on("data", function(data) {
jsonString += data;
});
req.on("end", function() {
console.log("data from frontend", JSON.parse(jsonString));
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE"
});
res.write("\n[request received successfully]\n");
res.end();
});
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("No Page Found");
}
})
.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
})();
Singura dependință pentru backend este node-persist, ceva asemănător cu localStorage din browser.