HTTP Cach Control header not caching

43 Views Asked by At

I have node js with express server. when i try simple api call it does caching the response but when i involve cors , somthing happens and the response doesnt caching. (i dont know if its only from cors ).

The app configuartion :

const app = express();
app.use(bodyParser.json());
app.use(cors);
app.use(cookieParser());

The Cors.ts:

export const allowedOrigins = [baseUrlFE,baseUrlFE2];

function cors(req: Request, res: Response, next: NextFunction) {
  const origin = req.headers.origin as string;
  if (allowedOrigins.includes(origin)) {
    res.setHeader("Access-Control-Allow-Origin", origin);
  }

  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization,  Cache-Control");

  // Allow requests to include cookies or authentication headers
  res.setHeader("Access-Control-Allow-Credentials", "true");

  next();
}

export default cors;

The working EP: (For this request i send request.mode as no-cors)

app.get("/test", (req, res) => {
  res.header("Cache-Control", "public, max-age=2592000");
  res.send({ urlBE: baseUrlBE, urlFE: baseUrlFE, env: process.env.NODE_ENV });
});

The non working EP is POST request which involving router and controller as follow:

app.use("/boo", BooRouter);

//in BooRouter.ts
const router = express.Router();
router.post("/ep2", fooController);

//in controller.ts
export const fooController = async (req: Request, res: Response) => {
  try {
    const results = await db.query("DO SOME FETCH FROM DB);
    console.log("request from server");
    res.header("Cache-Control", "public, max-age=2592000");
    res.json(results.rows);
  } catch (error: any) {
    res.status(500).json({
      type: error.name,
      message: error.message,
    });
  }
};

So from the BE point of view its hard to understand why the GET method works and the POST didnt.

as i mention earlier the main difference between the working and non working call is the the GET vs POST and the in the working call i also send mode: no-cors as follow:

From the FE (react)

const response = await fetch(urlBE + url, {
      method,
      credentials: "include",
      //mode: 'no-cors' for working EP , 'cors' didnt works
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token || ""}`,
        // "Cache-Control": "public, max-age=2592000",
      },
      body: BODY,
    });

**I know that POST method is a bit wierd with caching , but i know it possible. I do manage to cach same request with GET method , but i intrest to learn **

1

There are 1 best solutions below

1
Kenedy Nopriansyah On

You forgot, call cors, you can do like this

if you want give all access

app.use(cors({
   origin: '*'
}));

if you want give specific access

app.use(cors({ origin: 'https://example.com' }))

if you want give access multiple access

const allowlist = ['http://example1.com', 'http://example2.com']
const corsOptionsDelegate = function (req, callback) {
  let corsOptions = { origin: false };
  if (allowlist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  }

  callback(null, corsOptions) // callback expects two parameters: error and options
}

app.use(cors(corsOptionsDelegate))