I'm hosting a node.js backend and Postgres database on Heroku. After Heroku started requiring ssl, any requests to the database stopped working. I followed the documented fix here but I'm still getting errors. The request just hangs and eventually errors out as a CORS error.
"Access to XMLHttpRequest at [...] from origin [...] has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Database requests work locally both in browser and Insomnia. I also tried making new Heroku projects but still run into the same error when making database requests.
Here is my db.js:
const { Client } = require("pg");
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.connect();
module.exports = client;
app.js:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
// add logging system
const morgan = require("morgan");
app.use(morgan("tiny"));
const villagersRoutes = require("./routes/villagers");
const wakeRoutes = require("./routes/wake");
app.use("/villagers", villagersRoutes);
app.use("/", wakeRoutes);
/** 404 Not Found handler. */
app.use(function (req, res, next) {
const err = new Error("Not Found");
err.status = 404;
next(err);
});
/** Generic error handler. */
app.use(function (err, req, res, next) {
if (err.stack) console.error(err.stack);
res.status(err.status || 500).json({
message: err.message,
});
});
module.exports = app;
server.js:
const app = require("./app");
app.listen(process.env.PORT || 5000, function () {
console.log("Server is listening on port 5000");
});