// cros.ts
import { Request, Response, NextFunction } from 'express';
import { PREFLIGHT } from '../constants';
export function cros(request: Request, response: Response, next: NextFunction) {
// @ts-ignore
const { method, headers, logger, url } = request;
const allowHeaders = headers['access-control-request-headers'] || headers['Access-Control-Request-Headers'] || '';
const cropHeaders = {
'Access-Control-Allow-Origin': headers.origin || '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': `swimlane, ${allowHeaders}`,
'Access-Control-Max-Age': 600,
'Vary': 'Origin',
}
if (method.toLocaleLowerCase() === 'options') {
// 记录日志,便于线上定位问题
logger.info(PREFLIGHT, {
url,
result: JSON.stringify(headers)
});
response.statusCode = 204;
response.setHeader('Content-Length', '0');
for(var key in cropHeaders) {
response.setHeader(key, cropHeaders[key]);
}
response.end();
} else {
for(var key in cropHeaders) {
response.setHeader(key, cropHeaders[key]);
}
next();
}
};