0

I have a vue 3 SSR-SSG project. The original codes come from this directory that is from official Vue docs.

My project also have a back-end that is built with node. The main file of the back-end part is called server.js and the code of that is:

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

require('dotenv').config();
var cookieParser = require('cookie-parser')

var usersRoute = require('./app/route/user.js')

const pathFront = __dirname + '/client/dist/static';
console.log(pathFront);

const app = express()

app.use(cookieParser());

var whitelist = [process.env.BACK_URL, process.env.FRONT_URL]
var corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
    },
    credentials: true,
    optionsSuccessStatus: 200
}


// Add middleware for parsing JSON and urlencoded data
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

// Serve static files from the Vue app
app.use(express.static(pathFront));

// The "catchall" handler: for any request that doesn't
// match one above, send back Vue's index.html file.
//app.get('/*', (req, res) => {
//  res.sendFile(path.join(`${mainPath}/client/dist/static/index.html`))
//})

app.use('/api/v1', cors(corsOptions), usersRoute)

// catch 404 and forward to error handler
app.use((req, res, next) => {
    const err = new Error('Not Found')
    console.log(err)
    err.status = 404
    res.send('Route not found')
    next(err)
})

console.log(process.env.PORT, 'APP-PORT')

const server = app.listen(process.env.PORT || 3000).on('listening', () => {
    console.log(`App live and listening on port: ${process.env.PORT}` || 3000)
})

The pathFront variable defined above is used to determine the directory of "static" files that was generated with npm run generate command in Vue part. That folder (dist/static) contains some html files and a folder called assets. I used this technique before when I had a Vue2-SPA project. In that case these codes worked fine and I could deploy the vue part in the back-end of site (node part). But here when I want to serve a vue SSG app with express and node, it does not work. the routes in final app does not show correctly when I type http://localhost:3000 in the url of browser.

Also whan I right click on the page and select view page source, the message Route not found is appeared. In my command-line the message Not Found that comes from 404 codes in server.js file is shown. Is my implementation wrong? Does any developer have any idea of deploying a vue SSG app with node? I don't want to host front-end and back-end parts separately and also I want to use vue-router for routing pages in my app.

hamid-davodi
  • 1,602
  • 2
  • 12
  • 26

0 Answers0