Skip to content

Instantly share code, notes, and snippets.

@n9ti
Last active May 21, 2024 07:25
Show Gist options
  • Save n9ti/4162570990cb32db7f65d9dbf9e2b5b8 to your computer and use it in GitHub Desktop.
Save n9ti/4162570990cb32db7f65d9dbf9e2b5b8 to your computer and use it in GitHub Desktop.
Setup Express.js with Vue.js SPA
// config/index.js
module.exports = {
// ...
dev: {
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
}
}
}
{
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js & nodemon server/index.js",
"start": "npm run build && NODE_ENV=production node server/index.js",
"unit": "jest --config test/unit/jest.conf.js --coverage",
"test": "npm run unit",
"lint": "eslint --ext .js,.vue src test/unit",
"build": "node build/build.js"
}
}
// server/index.js
const express = require('express')
const api = require('./api')
const path = require('path')
const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
app.set('port', port)
// Import API Routes
app.use('/api', api)
// Serve Vue.js as SPA in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('dist'))
app.get('*', (req, res, next) => {
res.sendFile('index.html', {'root': path.join(__dirname, '../dist')})
})
}
// Listen the server
app.listen(port, host, () => {
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment