Using Angularjs to route ejs static files located in the "views" folder from the "public" folder of express.js

My current project structure can be seen here: https://i.stack.imgur.com/TdqoN.png

I am encountering an issue where I am trying to access the ejs file (list.ejs) located within the "views" folder from my angular routing file (main.js) in the "public" folder. Unfortunately, the list.ejs file is not loading.

/************main.js****************/
var fsApp=angular.module('chart-app');
fsApp.config(function($routeProvider) {
 $routeProvider
 .when('/', {
templateUrl: 'list.ejs',
controller: 'listCtrl'
})

/*In my server.js server file I am calling the files in public folder this way: */
app.use('/static',express.static(__dirname + '/public'));
app.get('/',function(req,res){
  res.render('index.ejs');
});
<!--In index.ejs (where my <ng-view></ng-view> is) I am including the link for static files:-->

<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script src="/static/angular-route.js"></script>
<script src="/static/main.js"></script>
</head>
<body ng-app="chart-app" class="container-fluid">
<div ng-controller="fairshareCtrl">
<div class="row" ng-view></div>
</div>
</body>

I'm wondering if there are additional steps that need to be taken in the server file. What could be causing the issue?

Answer №1

If you're unsure about the backend technology being used, remember that when rendering an ejs file from express, you need to specify the engine for it.

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

Then, implement the following:

app.get('*', function(req, res) {
   res.render('index.ejs');
});

It's recommended to store all Angular-related files in a public folder.

Alternatively, you can choose to load an HTML file instead of ejs using the following method:

app.engine('html', require('ejs').renderFile);

app.get('*', (req, res) => {
    res.render('index.html');
})

Answer №2

Public folders have limitations in accessing files outside of their designated area, such as folders like node_modules, views, and routes. This is why loading list.ejs from your angular main.js or angular-route.js file may not be possible.

Views are utilized by express to render view templates (ejs) based on incoming requests sent to the backend. These views cannot be used for frontend routing and can only be accessed by the express app, not the public folder.

For frontend routing, it is recommended to keep all templates within your public folder exclusively.

To address this issue, consider creating a templates folder inside your public directory and utilize that path for angular routing:

public  
  --templates
     --list.html
  --angular-route.js
  --main.css
  --main.js

In your angular routing code, reference the template like so:

fsApp.config(function($routeProvider) {
 $routeProvider
 .when('/', {
    templateUrl: 'templates/list.html',
    controller: 'listCtrl'
})

If needed, include ejs.js in your view file to support ejs templating in frontend. Refer to ejs getting started doc for guidance on how to set this up.

I trust this information will prove helpful to you.

Answer №3

To ensure that EJS searches the correct directory, I needed to include

app.set('views', path.join(__dirname, '/public'));
. This allowed EJS to look in the public folder instead of the default views folder.

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

Stop mongoose from inserting template schema into the database

Currently, I am in the process of developing a demonstration gaming web application using express and mongoose. Within this app, there are various game types available, including quizzes and puzzles. My objective is to establish a primary Schema named Gam ...

Gatsby Functions: Exceeding payload size limit error - request entity too large

I am currently working on a Gatsby app and utilizing Gatsby Functions to obscure form submissions to an external API. The issue I am facing is that when a user attaches a file in the form, it could potentially surpass the default size limit of 100KB. While ...

Is it possible to incorporate a setup phase in an express application?

Is it possible to create an array named res.locals.messages that stores messages generated in routes, like "phone number added to user"? Can a setup stage be established before any routes are executed to initialize this array? Are there more efficient meth ...

What is the process for installing vue-cli?

I'm currently diving into the world of Node Package Manager and Vue, trying to wrap my head around the Vue CLI. On the vue.js website, they provide instructions for running the official Vue CLI: https://i.stack.imgur.com/0OCrc.png I have a few inqu ...

send email with .jpg image attachment through AWS SES using node.js

Check out the code snippet below from https://github.com/andrewpuch/aws-ses-node-js-examples, which provides an example of sending an email with an attachment. I made some modifications to the code in order to retrieve an image file from AWS S3 and send i ...

Having trouble removing a column using type-orm migration

Having encountered an issue with a test entity, wherein the creatorId field was meant to be changed from integer to string, but even after migration it remained as type int. To address this, I decided to remove the problematic field completely and introduc ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...

The command 'prefix -g' is encountering an error and is not recognized as a valid command during the installation process of Angular

Microsoft Windows [Version 10.0.16299.309] (c) 2017 Microsoft Corporation. All rights reserved. C:\Users\Futluz>cd desktop/angular-cli-master/angular-cli-master C:\Users\Futluz\Desktop\angular-cli-master\angular-cli-mas ...

Struggling to load JS or CSS files in EJS, Express, and NodeJS

I'm delving into the world of EJS, Node, and Express (completely new to all three). Below you'll find my ejs file, app.js file, and directory structure. Could someone please guide me on properly setting things up? Appreciate your help in advance. ...

What are the steps for upgrading the Mongodb Nodejs driver to the newest version?

Can someone please provide guidance on how to easily update the mongodb nodejs driver to the latest version? I have attempted using only npm install mongodb, but it does not seem to upgrade to the most recent driver version. I am currently working in the ...

The map function appears to be malfunctioning or there may be an issue with the retrieved data

Encountering an error message that says "Cannot read properties of undefined (reading 'map')" while attempting to render a list. Below is the code snippet, seeking assistance. import React, { Component } from 'react' // import axios fro ...

Which file from Next.js should I statically serve using Node?

Whenever I work with React, my standard process includes running npm build, moving the content to a directory named public in Node, and then including the following code snippets: node/app.js app.use(express.static(path.join(__dirname, 'public') ...

What is preventing the command "npm run <command>" from functioning properly?

npm run is failing to work on any project, preventing me from installing packages with post-installed scripts. The error message displays details about the npm CLI and paths involved in running tests. 0 info it worked if it ends with ok 1 verbose cli ... ...

Can you explain the concept of BuildOptions in Sequelize?

Despite poring through the sequelize documentation and conducting extensive searches online, I have yet to come across a satisfactory answer: Why is BuildOptions necessary and what impact does it have on the created model? import { Sequelize, Model, Data ...

Encountered a Stdout maxBuffer error during the execution of a Gulp task

Recently, as I was setting up a new Backbone project and utilizing Gulp for task automation, a frustrating issue arose. Whenever I ran my task involving Browserify and gulp-compressor, an error message mentioning "stdout maxBuffer" would appear. In my app. ...

Unable to compile an Ionic 5 (angular) application with Node.js versions 12.22.12 or 12.22.6

I'm facing a challenge with an old app that requires me to run it using nvm for compatibility with older versions of node.js and ionic. Despite the outdated dependencies, I simply need to get it running in a development environment. Upon attempting t ...

Making a Button-triggered Post Request in NodeJS

I am unsure if this is achievable, but after conducting research, it seems that using a form and text input can make it possible. My goal with NodeJs & Express is to have the ability to send a post request to my Node.JS server when a button on my webpage i ...

Guide to building an Ember 2.8.0 project

Currently working on setting up an Ember 2.8.0 project. Having trouble finding specific guidance in the Ember.js documentation for this version. : ( Checked out some solutions on stackoverflow, but none of them seemed to work as expected or were marked a ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

NodeJS encountered an error due to the absence of a file or directory at the specified path: 'C:UsersIdoDesktopSemestrialNodeJSpubliclogin.html'

Image description hereI am currently working on a NodeJS project, and I am facing an issue when trying to access the login page. Whenever I try to go to /login, an error message pops up saying: Error: ENOENT: no such file or directory, stat 'C:&bsol ...