Created
October 30, 2018 03:25
-
-
Save crrobinson14/28356e52e51424915c268845c2eb518e to your computer and use it in GitHub Desktop.
ActionHero v19+ CORS middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Initializer, api } = require('actionhero'); | |
// Adjust to suit... Or optionally move into config... | |
const allowedOrigins = [ | |
'https://staging.mydomain.com', | |
'https://www.mydomain.com', | |
'https://mydomain.com', | |
'http://localhost:8080', | |
]; | |
const fallbackOrigin = 'https://www.mydomain.com'; | |
const setHeaders = (connection, origin) => { | |
const { responseHeaders } = connection.rawConnection; | |
const setOrigin = allowedOrigins.indexOf(origin) !== -1 ? origin : fallbackOrigin; | |
responseHeaders.push(['Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, DELETE, OPTIONS']); | |
responseHeaders.push(['Access-Control-Allow-Origin', setOrigin]); | |
}; | |
const processCORS = data => { | |
const { action, connection } = data; | |
if (action === 'getSystemStatus') { | |
return; | |
} | |
const rawConnection = connection.rawConnection || {}; | |
const headers = (rawConnection.req || {}).headers || {}; | |
setHeaders(connection, headers.origin); | |
}; | |
module.exports = class CORS extends Initializer { | |
constructor() { | |
super(); | |
this.name = 'CORS'; | |
this.loadPriority = 1000; | |
this.startPriority = 1000; | |
this.stopPriority = 1000; | |
} | |
async start() { | |
// Check incoming requests for authentication requirements | |
// NOTE: Doesn't work because OPTIONS requests don't get processed through middleware. Left here as | |
// documentation for that fact. | |
api.actions.addMiddleware({ | |
name: 'Request Processing : CORS', | |
global: true, | |
priority: 50, | |
preProcessor: processCORS, | |
}); | |
const webServer = api.servers.servers.web; | |
webServer.respondToOptions = connection => { | |
const { origin } = connection.rawConnection.req.headers; | |
setHeaders(connection, origin); | |
webServer.sendMessage(connection, ''); | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I never got this working, but I also wanted to share this error I ran into incase anyone else does:
actionhero/actionhero#2032