You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Express.js向Vue.js前端发送数据?附后端代码示例

Hey there! Let's figure out how to pass data from your Express backend to your Vue frontend when serving the dist/index.html file. Here are a few practical approaches you can pick based on your needs:

This is the standard approach for Vue single-page apps. After the frontend loads, it makes an API call to fetch the data from Express. It keeps your frontend and backend decoupled, which is ideal for SPA workflows.

Step-by-Step Implementation:

First, update your server.js to add an API endpoint that returns your data:

var express = require('express');
var app = express();
var path = require('path');

// Serve static files from dist
app.use(express.static(__dirname + '/dist'));

// Add an API endpoint to send initial data
app.get('/api/initial-data', (req, res) => {
  const dataToSend = {
    username: 'Ace',
    appVersion: '1.0.0',
    featureFlags: { darkMode: true, notifications: false }
  };
  res.json(dataToSend);
});

// Catch all other routes and return index.html (for Vue's SPA routing)
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '/dist/index.html'));
});

app.listen(80);

Then, in your Vue component (e.g., App.vue), fetch the data when the component mounts:

<template>
  <div id="app">
    <h1>Welcome back, {{ appData.username }}!</h1>
    <p>Current App Version: {{ appData.appVersion }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      appData: {}
    };
  },
  async mounted() {
    try {
      // Use fetch (or axios if you prefer) to get data from the API
      const response = await fetch('/api/initial-data');
      this.appData = await response.json();
    } catch (error) {
      console.error('Failed to load initial data:', error);
    }
  }
};
</script>

2. Inject Data via Template Engine (For Pre-Rendered Data Needs)

If you need data to be available as soon as the page loads (like for SEO or critical initial config), you can convert your index.html into a template and let Express inject data during rendering. We'll use EJS here, but you can use any template engine you like.

Step-by-Step Implementation:

  1. Install EJS first:
npm install ejs
  1. Update your server.js to configure the template engine and render the template with data:
var express = require('express');
var app = express();
var path = require('path');

// Set EJS as the template engine
app.set('view engine', 'ejs');
// Point to your dist folder where the template will live
app.set('views', path.join(__dirname, '/dist'));

// Serve static assets (CSS, JS, images from dist)
app.use(express.static(__dirname + '/dist'));

// Render the template and pass data
app.get('*', (req, res) => {
  const initialData = {
    siteTitle: 'My Vue + Express App',
    user: { id: 456, name: 'Ace' }
  };
  // Pass data as a stringified JSON to avoid syntax issues
  res.render('index', { initialData: JSON.stringify(initialData) });
});

app.listen(80);
  1. Rename dist/index.html to dist/index.ejs, then add a script tag in the <head> to inject the data as a global variable:
<head>
  <!-- ... your existing meta tags, links ... -->
  <script>
    window.__INITIAL_DATA__ = <%- initialData %>;
  </script>
</head>
  1. Access the data in your Vue component:
<template>
  <div id="app">
    <h1>{{ initialData.siteTitle }}</h1>
    <p>Logged in as: {{ initialData.user.name }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      initialData: window.__INITIAL_DATA__ || {}
    };
  }
};
</script>

3. Manual HTML Replacement (No Template Engine Needed)

If you don't want to use a template engine, you can manually read the index.html file, replace a placeholder with your data, and send the modified HTML to the client.

Step-by-Step Implementation:

Update your server.js to read and modify the HTML file:

var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs');

// Serve static files from dist
app.use(express.static(__dirname + '/dist'));

// Handle all routes by injecting data into index.html
app.get('*', (req, res) => {
  fs.readFile(path.join(__dirname, '/dist/index.html'), 'utf8', (err, htmlContent) => {
    if (err) {
      return res.status(500).send('Error loading page');
    }

    const initialData = {
      greeting: 'Hello from Express!',
      appConfig: { debug: false }
    };

    // Replace a placeholder in index.html with the data script
    const updatedHtml = htmlContent.replace(
      '<!-- INITIAL_DATA_PLACEHOLDER -->',
      `<script>window.__INITIAL_DATA__ = ${JSON.stringify(initialData)}</script>`
    );

    res.send(updatedHtml);
  });
});

app.listen(80);

Add the placeholder in your dist/index.html <head>:

<head>
  <!-- ... existing content ... -->
  <!-- INITIAL_DATA_PLACEHOLDER -->
</head>

Then access the data in Vue the same way as the template engine approach (using window.__INITIAL_DATA__).


Quick Recommendation:

Go with Option 1 if you're building a typical Vue SPA—it's clean, follows best practices, and keeps your frontend/backend separate. Use Options 2 or 3 only if you need data to be available before the Vue app mounts (like for SEO or critical initial setup).

内容的提问来源于stack exchange,提问作者Ace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:17:09