Search code examples
javascriptnode.jsexpressvuejs2vue-resource

Vue-resource can't load express static file


So, I have a bit of a problem. Here's my server.js

require('dotenv').load();
const http = require('http');
const path = require('path');
const express = require('express');

const app = express();



const server = http.createServer(app).listen(8080, () => {
    console.log('Foliage started on port 8080');
});

app.use(express.static(path.join(__dirname, '/public')));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

What this does, is that for every /whatever it gives the index.html file. Alongside that, it serves static files from /public Now, my index.html looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Foliage</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/foliage.css" media="screen" title="no title">
        <script src="https://use.fontawesome.com/763cbc8ede.js"></script>
    </head>
    <body>
        <div id="app">
            <router-view :key="$router.currentRoute.path"></router-view>
        </div>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
        <script src="js/md5.js"></script>
        <script src="js/cookies.js"></script>
        <script src="js/dragula.js"></script>
        <script src="js/build.js"></script>

    </body>
</html>

All of the JS files and the style files are loaded appropriately from public/jsand public/css for this. However, in build.js, which is a webpack-ed vuejs app, I use vue-resource, to load in another file from public/themes/Bareren/templates. That looks like this

page = {};
page.Template = "Index";   
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response) => {
      console.log(response.body);
});

However, this request does not give me the file in public/themes/Barren/templates. It instead gives back the site's own index.html file. How could i fix this?


Solution

  • app.use(express.static(path.join(__dirname, '/public')));

    app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'index.html')); });

    app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'index.html')); });

    Try to console.log(path.join(__dirname, '/public')) and console.log(path.join(__dirname, 'index.html') to see if the path matches what you are expecting.

    this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response) => { console.log(response.body); });

    You can also try console logging your get request. Usually I need to play with the pathing to making sure I'm serving the correct files.