Last active
September 18, 2019 17:44
-
-
Save shriker/a7d2e150d6b26882c76b918dfd7a6c27 to your computer and use it in GitHub Desktop.
Vue API forward to nodejs backend
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
// vue.config.js | |
process.env.APP_VERSION = require('./package.json').version; | |
module.exports = { | |
/* webpack dev configuration */ | |
devServer: { | |
host: '0.0.0.0', | |
port: 8080, | |
https: false, | |
hotOnly: false, | |
proxy: null, // string | Object | |
before: app => { | |
// Forwards api requests to backend | |
app.use((req, res, next) => { | |
if (!req.url.startsWith('/api')) return next(); | |
// Delete cached backend scripts to allow for hot-reload | |
for (let path of Object.keys(require.cache)) { | |
if (path.includes('backend')) { | |
delete require.cache[path]; | |
} | |
} | |
let path = req.url.replace(/\/api/, '').split('?')[0]; | |
var id = ''; | |
path.split('/').map(it => { | |
if (/\d/.test(it)) id = it; | |
}); | |
var event = { | |
path: path, | |
httpMethod: req.method, | |
headers: req.headers, | |
queryStringParameters: req.query, | |
pathParameters: { | |
id: id | |
} | |
} | |
var body = Buffer.from(''); | |
req.on('data', chunk => { | |
body = Buffer.concat([body, chunk]); | |
}); | |
req.on('end', () => { | |
if (req.is('multipart/form-data')) { | |
event.body = body.toString('base64'); | |
event.isBase64Encoded = true; | |
} else { | |
event.body = body.toString(); | |
} | |
let index = require('./backend/index'); | |
index.handler(event, null, (err, result) => { | |
if (err) { | |
res.status(500).send(err); | |
} else { | |
res.status(result.statusCode).set(result.headers); | |
if (result.isBase64Encoded) res.end(Buffer.from(result.body, 'base64'), 'binary'); | |
else res.end(result.body); | |
} | |
}); | |
}); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment