Skip to content

Instantly share code, notes, and snippets.

@kilgarenone
Last active April 28, 2020 14:16
Show Gist options
  • Save kilgarenone/8402f4aabb3bc248ba4121ffb4b85f21 to your computer and use it in GitHub Desktop.
Save kilgarenone/8402f4aabb3bc248ba4121ffb4b85f21 to your computer and use it in GitHub Desktop.
server.js
const express = require("express");
const cors = require("cors");
const createError = require("http-errors");
const app = express();
const isProduction = app.get("env") === "production";
if (isProduction) {
app.set("trust proxy", 1);
}
app.disable("x-powered-by");
app.set("port", process.env.PORT || 4000);
app.use(express.urlencoded({ extended: true }));
const ALLOWED_ORIGINS = ["http://localhost:8008", "https://web.sametable.app"];
app.use(
cors({
credentials: true, // include Access-Control-Allow-Credentials: true. remember set xhr.withCredentials = true;
origin: function (origin, callback) {
// allow requests with no origin
// (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (ALLOWED_ORIGINS.indexOf(origin) === -1) {
const msg =
"The CORS policy for this site does not " +
"allow access from the specified Origin.";
return callback(new Error(msg), false);
}
return callback(null, true);
},
})
);
// could be one of your API endpoints for your client
app.get('/', (req, res) => {
// do stuff
})
// central custom error handler
// NOTE: DON"T REMOVE THE 'next'!!!!!
app.use(function (err, req, res, next) {
const error = createError(500, "Something went wrong. Alerted developer");
res.status(error.status).json(error);
});
process.on("unhandledRejection", (reason, p) => {
// Error not caught in promises(ie. forgot the 'catch' block) will get swallowed and disappear.
// I just caught an unhandled promise rejection,
// since we already have fallback handler for unhandled errors (see below),
// let throw and let him handle that
throw reason;
});
// mainly to catch those from third-party lib. for own code, catch it in try/catch
process.on("uncaughtException", function (err) {
process.exit(1);
});
app.listen(app.get("port"), () => {
console.log(`🚀 We are live at locahost:${app.get("port")} 🚀 `);
process.send("ready");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment