javascript - Vue-resource 无法加载 express 静态文件

标签 javascript node.js express vuejs2 vue-resource

所以,我有一点问题。这是我的 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'));
});

它的作用是为每个 /whatever 提供 index.html 文件。除此之外,它还提供来自 /public 的静态文件。现在,我的 index.html 看起来像这样:

<!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>

为此,所有 JS 文件和样式文件都从 public/jspublic/css 适本地加载。但是,在 build.js 中,这是一个 webpack-ed vuejs 应用程序,我使用 vue-resource 从 public/themes/Bareren/templates 加载另一个文件。看起来像这样

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

但是,这个请求并没有给我public/themes/Barren/templates中的文件。相反,它返回站点自己的 index.html 文件。我该如何解决这个问题?

最佳答案

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')); });

尝试 console.log(path.join(__dirname, '/public')) 和 console.log(path.join(__dirname, 'index.html') 查看路径是否符合您的预期。

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

您还可以尝试控制台记录您的获取请求。通常我需要使用路径来确保我提供的是正确的文件。

关于javascript - Vue-resource 无法加载 express 静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439518/

相关文章:

asp.net - 如何在javascript中设置定时间隔?

javascript - var self = 这个?

javascript - 按钮打破 react 形式

javascript - MongoDB,从数组中删除对象

javascript - 您如何使用 Express 访问 Axios 响应?

json - 查询Mongodb子文档错误将循环结构转换为JSON

javascript - jQuery 是否为每个具有 id 的元素创建一个全局范围的对象?

javascript - 添加 key :value to a . json 文件

java - maven中的npm install相当于什么

node.js - 我正在 Node.js 上开发 Express 4 应用程序。我在渲染新 View 时遇到问题