Skip to content

Commit

Permalink
add cdnjs & add Access-Control-Allow-Origin header
Browse files Browse the repository at this point in the history
  • Loading branch information
Muska-Ami committed Dec 23, 2023
1 parent 5f3231d commit 42ac31d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
11 changes: 11 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@ const proxy_router = require('./src/router');
dotenv.config();
const app = express();

app.use((req, res, _next) => {
res.header('Access-Control-Allow-Origin', '*');
_next();
})

proxy_router.load(app);

app.use((req, res, _next) => {
res.status(403);
res.header('Content-Type', 'application/json');
res.end('{"status": false}');
});

app.listen(process.env.PORT, process.env.HOST, () => {
console.log(`Server running at http://${process.env.HOST}:${process.env.PORT}`);
});
22 changes: 22 additions & 0 deletions src/proxies/cdnjs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const { createProxyMiddleware } = require('http-proxy-middleware');

const options = {
target: 'https://cdnjs.cloudflare.com',
pathRewrite: {
'^/cdnjs/': '/'
},
onProxyRes: onProxyRes,
changeOrigin: true
}

function onProxyRes(proxyRes, req) {
//console.log(proxyRes.headers);
if (proxyRes.headers['location']) {
// 修改Location重定向
let hl = proxyRes.headers['location'];
delete proxyRes.headers['location'];
proxyRes.headers['location'] = `/cdnjs${hl}`;
}
console.log(`[PROXY][CDNJS] /cdnjs${req.path} => ${req.path}`);
}
module.exports = createProxyMiddleware(options);
4 changes: 4 additions & 0 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ const proxies = [
{
name: 'jsdelivr',
path: '/jsd/'
},
{
name: 'cdnjs',
path: '/cdnjs/'
}
]

Expand Down

0 comments on commit 42ac31d

Please sign in to comment.