Skip to content

Instantly share code, notes, and snippets.

@shriker
Last active September 18, 2019 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shriker/a7d2e150d6b26882c76b918dfd7a6c27 to your computer and use it in GitHub Desktop.
Save shriker/a7d2e150d6b26882c76b918dfd7a6c27 to your computer and use it in GitHub Desktop.
Vue API forward to nodejs backend
// 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