M
M
MahoroYo2020-02-04 13:05:57
Layout
MahoroYo, 2020-02-04 13:05:57

How to combine Vue and Express in SPA?

There is a node server with express, there is vue with vue-router and several paths in it.
Server code:

// Подключение библиотек
const express = require('express');
const mysql = require('mysql2');
const path = require('path');
const history = require('connect-history-api-fallback');

// Конфигурации
const config = require('./config/config.js')
const app = express();
// парсинг запросов
app.use(express.json())
// статические файлы в корне директории сервера
// app.use(express.static('public/dist'))
app.use(express.static(config.static.dirVue))
app.use(history());

// страницы html для рендеринга
const page = {
    'index': path.resolve(config.static.dirVue, 'index.html')
}

// запустить сервер
app.listen(process.env.PORT || config.server.port, () => {
    console.log(`server start on ${config.server.port} port`);
    console.log(`127.0.0.1:${config.server.port}`);
})

app.get('*', (req, res) => {
    // console.log(req.params);
    res.sendFile(page.index);
})


This code allows you to send a Vue build assembly to the client with the requested route, but the problem is that the server does not respond to any other ajax request.
Thus, how can you make express send not only html (with routes), but also have access to the api of the same server?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hzzzzl, 2019-05-17
@hzzzzl

https://codepen.io/anon/pen/zQzYxr

A
Alex, 2020-02-04
@Kozack

Documentation and guides on the same topic will help you: https://expressjs.com/ru/guide/routing.html

D
de1m, 2020-02-04
@de1m

Look here , I began to redo it on vue and express, but then I changed my mind.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question