'How to use Express with Vue
First time using Node js, Express and Vue.
I have a pomodoro timer website made with vue (not vue-app/vue-cli) which I'm wanting to upload to Heroku. The website works perfectly locally with Webstorm IDE, but can't manage to make it work with Express.
Github link of project: https://github.com/marcelmiro/Pomodoro
This is how my files are organized:
+-- node_modules
-- vue & express modules
+-- scripts
-- main.css
-- main.js (where my vue code is)
-- bundle.js (me testing how to use a webpack. its not being used atm)
+-- assets
-- all images
+-- index.html
+-- package.json
+-- Procfile
+-- server.js
server.js:
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
app.use("/scripts", express.static("scripts"));
app.get('/', (req, res) => res.sendFile(__dirname + "/index.html"));
app.listen(port, () => {
console.log('Server connected at:',port);
});
So I can manage to load css (although not all css code), but not main.js (where my vue code is). Images are also not loaded.
How can I solve this?
Solution 1:[1]
As index.html
is in your root folder, you just need to tell express to look there;
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
app.use('/', express.static(__dirname));
app.listen(port, () => {
console.log('Server connected at:',port);
});
In practice you would want to separate your source code from your production code, but that's a little out of scope for this question.
Solution 2:[2]
If you're using Vue to create a single page application, you might be using history mode. In that case, here is a full solution with ssl and http redirects to https:
/* server.js */
const fs = require('fs')
const https = require('https')
const http = require('http')
var express = require('express')
const history = require('connect-history-api-fallback');
const app = express()
const redirectHttp = express()
/*
* Redirect http to https
*/
redirectHttp.get("*", (req,res,next) => {
res.redirect("https://" + req.headers.host + req.url)
})
// USE HMTL5 History API, allows Vue to handle the routing
const staticFileMiddleware = express.static("./dist");
app.use(staticFileMiddleware);
app.use(history({}));
app.use(staticFileMiddleware);
http.createServer(redirectHttp).listen(80,()=>{console.log('Listening for http requests...')})
https
.createServer(
{
key: fs.readFileSync('path/to/key'),
cert: fs.readFileSync('path/to/cert'),
ca: fs.readFileSync('path/to/cert'),
},
app
)
.listen(443, () => {
console.log('Listening for https requests...')
})
This assumes your dist directory is in the same folder as server.js
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | paddyfields |
Solution 2 |