I'm setting up a dev server for a new open source project I'm working on: P2P VPS.
I needed to enable CORS on the server so that my dev box could communicate with it. The first thing I tried was this old article that covers it, but it didn't work. Something had changed in KeystoneJS core since I wrote that article. However these two threads lead me to get CORS working for the regular API routes, like ConnextCMS uses.
However, I wasn't after the regular API routes. I was after the new(ish) Admin API in KeystoneJS core. This API allows one to log in remotely, which is what I would need while developing the Vue.js application on my dev box.
As it turned out, I needed to edit the node_modules/keystone/admin/server/app/createDynamicRouter.js
file in my KeystoneJS installation, and add these lines to it:
if (keystone.get('healthchecks')) {
router.use('/server-health', require('./createHealthchecksHandler')(keystone));
}
router.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Init API request helpers
router.use('/api', require('../middleware/apiError'));
router.use('/api', require('../middleware/logError'));
Inside the keystone.js
file in the root directory of my project folder, I needed to add this setting:
keystone.set('cors allow origin', true);
After restarting the KeystoneJS software, I could now make an AJAX call to the Admin API, like this:
$.get('http://p2pvps.net/keystone/api/session', '', function(data){debugger;})