Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I'm having a hard time solving CORS error lately and I admit that I'm still learning express and server programming. I'm trying to submit a payload to the database but once I'm requesting on the server, chrome returns the error on the title. I've tried several fixes like adding wildcard on the origin of corsOptions, following the guide of cors https://github.com/expressjs/cors. I even added a require cors on one of my route file but still not working.
Here's the current code that I'm working with
index.js
const corsOptions ={
origin:'http://localhost',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
const app = express();
app.use(cors(corsOptions));
app.use(express.json());
const { StatusCodes, ReasonPhrases } = require("http-status-codes");
app.use(cors());
const server = http.createServer(function (req, res) {
console.log('A request was made: ' + req.url);
res.writeHead(200, {'Content-Type': 'text-plain'});
res.end('Response ended'); // ends the response
});
server.listen(3000, 'localhost');
app.get("/", (req, res) => {
res.status(StatusCodes.OK).json({
title: "Waiting for request...",
status: StatusCodes.OK,
});
});
const ups = require('./routes/ups.js');
app.use("/ups", cors(), ups);
app.all("*", (req, res, next) => {
res.status(StatusCodes.METHOD_NOT_ALLOWED).json({
status: StatusCodes.METHOD_NOT_ALLOWED,
title: ReasonPhrases.METHOD_NOT_ALLOWED,
});
next();
});
ups.js
const cors = require('cors');
const { StatusCodes, ReasonPhrases } = require("http-status-codes");
module.exports = () => {
router.post("/ups", cors(), (req, res) => {
if(
req.body == null ||
req.body.id == null ||
req.body.available == null
) {
console.log("error");
}
var id = req.body.id;
var av = req.body.available;
//Perform Query Ops
var sql = "UPDATE `pc_status` SET available = " + av + " WHERE `id` = " + id + "";
db.query(sql, function(err, result) {
if (err) throw err;
console.log('record inserted');
console.log(req.body.id);
console.log(req.body.available);
//result.redirect(201 ,'/');
});
});
return router;
};