Skip to content

Instantly share code, notes, and snippets.

@shriker shriker/vue.config.js
Last active Sep 18, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.