What is the best way to display a template from a directory that does not include express.static files?

Here is my loginController:

var User = require('./../models/User.js');

var loginController = {};

loginController.match = function(req, res){

    var username = req.body.username;
    var password = req.body.password;

    User.findOne({username : username, password : password})
    .then(function(user){
        if(user){
            res.render('profile',{
                title : 'Profile',
                user : user
            });
            /*return res.status(200).json({
                success : true,
                data : user
            });*/
        }
        else{
            return res.status(200).json({
                message : "Either username or password is wrong"
            });
        }
    })
    .catch(function(err){
        return res.status(500).json({
            message : err
        })
    });
}

module.exports = loginController;

After submitting the login credentials, the loginController runs the validation. If the validation is successful, it renders the profile.handlebars file successfully. However, there's an issue with consuming CSS that is served using express.static from a separate file (app.js).

Contents of app.js:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var hbs = require('express-handlebars');
var Path = require('path');

var routes = require('./routes.js');
var app = express();

/*View Engine*/
app.engine('handlebars',hbs({defaultLayout : 'layouts.handlebars', layoutsDir : __dirname + './../views/layouts'}));
app.set('views', Path.join(__dirname, './../views'));
app.set('view engine', 'handlebars');

/*Serve Static files*/
app.use(express.static(__dirname+'./../public'));

mongoose.connect('mongodb://localhost/tournament', function(){
    console.log('connected to tournament..');
});

/*Template Routes*/
/*Login*/
app.get('/', function(req,res,next){
    res.render('login',{
        title : 'Login'
    });
})
/*Profile
app.get('/profile',function(req,res,next){
    res.render('profile',options)
});
*/


app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret : "asdasdvbvc234234sdfsdf23213123", resave : false, saveUninitialized : true}));
app.use('/api', routes);

module.exports = app;

Contents of profile.handlebars:

<div class="row">
    <div class="col-md-12">
        <div class="float-right">
            Hello, {{user.username}}
            <button class="btn btn-md btn-danger">Logout</button>
        </div>
    </div>
</div>

Answer №1

To improve your code, consider updating

app.use(express.static(__dirname+'./../public'));
to
app.use(express.static(Path.join(__dirname, './../public')));

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

Starting the Android System Magnifier with a Click: A Step-by-Step Guide

Is there a way to incorporate a magnifying glass into an HTML page using jQuery or within an Android app? Ideally, it would be for a single picture. In my application, I am displaying an HTML file from my assets in a webview. The HTML page utilizes jQuery ...

Uncovering the Mystery Behind the Repetitive Execution of useEffect in Next.js

I am working on a Time Tracking feature for my Next.js application. In the ./app/components/TimeTracking.tsx file, I have implemented the following component: 'use client'; import React, { useEffect, useState } from 'react'; import { u ...

Tips for creating a puzzling effect with shadow as you move

When I work on my jigsaw puzzle game, I encounter an issue where the shadow of the parts moves with them when I try to scroll or move them. The problem looks like the image linked here: https://i.sstatic.net/3xhwY.jpg I attempted to use the code canvas.c ...

Best Practices for Showing JSON Data from MongoDB in an Angular Material Table

Desire I'm trying to extract data from MongoDB and exhibit it in an Angular Material Table. Problem Even though I can view the results of my MongoDB query in the console/terminal, the Chrome browser console indicates that my JSON data has been save ...

What is the best way to convert all JS, CSS, and IMG files to a static subdomain

Here are some files that I have: sub.domain.com/js/test.js sub.domain.com/image1.jpg sub.domain.com/test.css I want to rewrite all these file types to start with: static-sub.domain.com/.... Can you help me with this? Thank you. ...

Creating objects utilizing the asynchronous map method in JavaScript for data iteration

Within an async Immediately Invoked Function Expression (IIFE) in this JavaScript code, the goal is to: 1) read a JSON file, 2) extract multiple RSS feed URLs from the data, 3) fetch and parse information from those feeds, and generate an object containing ...

You must use the 'new' keyword to invoke the class constructor NextResponse | Implementing middleware in Next.js | Implementing role-based protection for routes in Next.js |

I've been working on implementing user role-based protected routes in my next.js project using middleware.js, but all of a sudden, I've encountered this issue. I'm not exactly sure why this is happening, so if anyone has a better approach to ...

The challenges of combining THREE.PlaneBufferGeometries in three.js r70

While attempting to utilize the recently introduced THREE.BufferGeometry.merge feature on buffer geometries created with THREE.PlaneBufferGeometry in r70, I encountered an error during the subsequent render call (although the merging process itself was err ...

Tips for preventing timeouts when posting data to Heroku servers

I have a Ruby on Rails application deployed on Heroku. The app includes 8 optional text fields that users can choose to fill or leave empty as needed. However, the more text fields a user fills out, the heavier the processing load on my app. If there are ...

Does the global $.ajaxSetup() function not impact $.ajax() calls within distinct functions?

Is it possible to make the effects of $.ajaxSetup() reach into function bodies? I'm having trouble getting $.ajaxSetup() to impact the $.ajax() calls within functions. Here is an example: In the code snippet below, the ajax request made by function f ...

Developing a fresh browser window with a clickable button using JavaScript

Currently, I am learning JavaScript and trying to create a button on a webpage using the code I wrote in JavaScript. However, instead of adding the button to the page specified by me, it is always added to index.html. I am using WebStorm IDE for this proje ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

The Jsoup function for sending data does not yield any results

Can someone assist me with sending data to a form in this format? <form id="money" action="" method="post"> <input id="user" type="text" placeholder="Username" maxlenght="10" name="user"></input> <div class="select"> <select id= ...

Understanding the structure of JSON files without prior knowledge

Without any prior knowledge of the contents, I am seeking to understand the structure of a JSON object. For example, I could receive: [{"x":0,"y":0.4991088274400681,"z":7.489443555361306}, {"x":0,"y":0.7991088274400681,"z":7.489343555361306},{"x":0,"y":0. ...

Sending a parameter from a click event to a function

Struggling with a jQuery and AJAX issue all night. I am new to both and trying to implement something similar to this example. I have an edit button with the ID stored in a data-ID attribute. Here's an example of what my button looks like: <butto ...

Steps to activate the image viewer for each individual looping image:

I'm struggling with my JavaScript code that fetches images and displays them in a modal view when clicked. The issue I'm facing is that the image view only works for the second and other images, but not for the first one. I know there are issues ...

Interested in learning how to code games using JavaScript?

Hi everyone, I'm currently exploring the world of Javascript and have been tasked with completing a game for a class project. The game involves a truck that must catch falling kiwis while only being able to move left or right. A timer is set for two m ...

CORS preflight request in Express.js was unsuccessful even after enabling CORS

Currently, I am utilizing a self-signed SSL certificate to operate an HTTPS server using Express. Below is my app.js code: const express = require('express'); const BodyParser = require('body-parser'); const config = require('./co ...

What category does React.js fall under - library or framework?

Hey there! I've noticed that sometimes people refer to React JS as a library, while others call it a framework. Can you shed some light on which term is more accurate? ...

Having difficulty configuring the option during the call back in the jQuery Plugin

I am working on implementing a customizable minHeight feature for my object. By default, the minHeight is set to be equal to the object's height. However, users have the option to change it using the plugin's configuration options during the cal ...