Steps for deploying Nuxt on a subdirectory using either Express JS or Plesk

I have configured my Nuxt (Node.js application) to run on Plesk. This means that Plesk will execute the server.js file, which in turn runs ExpressJS and then Nuxt. Here is the content of my server.js file:


const express = require('express')
const consola = require('consola')
const { Nuxt } = require('nuxt')
const app = express()
const port = process.env.PORT;

const config = require('./nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

async function start() {
  const nuxt = new Nuxt(config)
  const { host } = nuxt.options.server
  const port = process.env.PORT;
  await nuxt.ready()
  app.use(nuxt.render)
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true,
  })
}
start()

I am looking to serve Nuxt on sample.com/blog and serve a specific page at sample.com. How can I achieve this using ExpressJS or Plesk? I would prefer to use ExpressJS, but I am unsure how to proceed. Any help would be appreciated.

I have attempted to modify my server.js file with the code below, but it has not resolved the issue:


const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()

const config = require('./nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

async function start() {
  const nuxt = new Nuxt(config)
  const { host } = nuxt.options.server
  const port = process.env.PORT;
  await nuxt.ready()
  app.use(nuxt.render)
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true,
  })
}
 app.get('/blog',(req,res)=>{
 start()
 })
 app.get('/',(req,res)=>{
   res.send('Hello World!')
 })

 app.listen(port, ()=>{
   console.log(`Example app listening on port ${port}`)
 })

Currently, sample.com displays 'Hello World', but sample.com/blog returns an error.

Answer №1

My issue was resolved by implementing a server middleware redirect
point: To serve static sites, we need the serve-static package
Make sure to configure the serverMiddleware property in nuxt.confgi.js

 serverMiddleware: [
    { path: '/', handler: serveStatic(__dirname + '/staticSites/homePage') },
    { path: '/landing', handler: serveStatic(__dirname + '/staticSites/privacy') },
    { path: '/landing/Privacy.html', handler: serveStatic(__dirname + '/staticSites/privacy',{ index: ['Privacy.html'] }) },
    { path: "/app.apk", handler: "~/server-middleware/download.js" },
    { path: "/calorie.mp4", handler: "~/server-middleware/video_calorie.js" },
    { path: "/Zireh7.2.1-Sibapp.ipa", handler: "~/server-middleware/Zireh7.2.1-Sibapp.js" },
    '~/server-middleware/redirect.js'
  ],

To enable direct file downloads, use the code below in download.js

const path = require('node:path');
const app = require('express')()

    app.all('/', (req, res) => {
      const file = `${path.resolve()}/directDownload/app.apk`;
      res.download(file); // Set disposition and send it.
    })
    module.exports = app

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The standard date format used in Javascript/Jquery programs

I have a kendo date picker set to display dates in the format "MM/dd/yyyy". I need to use jquery or javascript to ensure that the selected date is not in the future and is greater than '01/01/1900'. The problem I'm encountering is handling ...

Error: Appwrite Login Authentication failed due to account.createEmailSession function not recognized as a valid function

Looking for help with Vue and Appwrite? Check out this tutorial: https://appwrite.io/docs/tutorials/vue/step-1 src/appwrite/index.js import { Client, Databases, Account } from "appwrite"; const client = new Client(); client .setEndpoint(" ...

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

Error: The call stack has reached its maximum size while running an npm install

Attempting to execute npm install, encountered the following console output: npm ERR! Linux 4.8.0-27-generic npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" npm ERR! node v6.9.1 npm ERR! npm v3.10.8 npm ERR! Maximum call stack size exceeded npm ...

What is the method for identifying the environment within an Express.js application?

Is there a reliable method for determining the environment in which an expressJS app is currently operating (development, test, production)? I have checked process.env, but found no clear indication of the environment. I know that variables can be set in ...

Downloading a PDF file received from a Django view using JavaScript and jQuery

I have a celery task that creates PDF files on the click of a button. When the button is clicked, the JavaScript side will keep checking until the task is done, and when it is, it will download the file. Some recursion should do the trick: $(".getPdf").o ...

Calculate the total price using jQuery

I’m a beginner in JavaScript and I’ve hit a roadblock. I have a plus and minus button that adds up product quantities, but I need the total price to reflect this as well. Some products can only be purchased in multiples of 2, 5 or 10. Here is the HTML ...

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...

Can you explain the functionality of isolate scope in angularjs?

I'm having trouble grasping the concept of scope : {}. Here's a snippet of code I've been working on. Why does it always display "strength" in the console instead of the actual array value? // Code goes here var app = angular.module("super ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Assign a value to the active textbox using JavaScript

Hello everyone, I am working on a page with three textboxes and one listbox. I would like to have functionality where if the user clicks on the first textbox and then selects an item from the list, that selected item should be automatically set as th ...

Tips for choosing a specific value that matches a property value within a JSON dataset

Is there a way to select a specific value in JSON based on another property value? For example, I would like to pass the configuration_code and retrieve the corresponding description. configurations: Array(2) 0: configuration_code: "SPWG" d ...

Navigating through Switch cases and If Statements with multiple arguments can be complex for beginners in the world of JavaScript

Hi there, I have a specific case that I'm struggling to find a solution for. I am using Angular with a Firebase back-end to retrieve true or false values from a variable called ref. The variable contains 4 properties with either true or false values - ...

Divide the output results into two equal horizontal sections within the same HTML table

Is there a way to dynamically split the output of a specific result into two horizontal sections that fit within the browser width? The number of rows returned from the service is variable, so a fixed solution won't work. I also want to avoid manually ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Ways to determine if a string or HTML contains repeated consecutive elements

Assume I am working with the following string <div id="ch">abcdefg<img /><img />hij</div> <div id="ad">abc<img />defg<img />hij</div> strHtml = $('div#ch').html(); strHtmlFalse = $('div#ad&ap ...

How come .trim() isn't cooperating with me?

I am encountering an issue with this particular piece of javascript. Every time I attempt to use it, nothing is displayed in my div. Instead, it simply adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL. <h2>What size d ...

Passport enchanted by the sails

I am currently in the process of integrating Passport strategies into a sails hook so that I can easily share them across multiple projects. However, when attempting to log in, I encountered the following error: Error: passport.initialize() middleware no ...

Using jQuery, extract the input value and verify its accuracy. If correct, display the number of accurately predicted results

I am attempting to extract the value from an input field and validate if the answer is accurate. Rather than simply indicating correctness, I aim to analyze and display the number of correct responses alongside incorrect ones. Encountering difficulties wit ...

Displaying colors using Javascript

When using node.js to create an HTML file from a js file, I am encountering an issue where the colors are not displaying in the output. I have generated hex values for the colors, but they do not appear in the HTML file as expected. var format; function ...