JS, Express: Encounter issues - unable to find view in directory despite following provided instructions

Currently, I am following the steps outlined in this guide:

Despite conducting extensive research, I am facing difficulty in getting it to work as expected.

Here is the folder structure I am working with: https://i.sstatic.net/jCEdO.png

Below is a snippet of my code:

// app.js

var express = require('express');
var app = express();
var port = 3000;

app.use(express.static('public'));

app.listen(port, function(){
  console.log('Server is running on port:', port);
})
app.get('/', function(req, res){
    res.send('Hello Express');
});


app.set('view engine', 'ejs');

var itemRouter = express.Router();

app.use('/items', itemRouter);

itemRouter.route('/').get(function (req, res) {
  res.render('items');
});

itemRouter.route('/single').get(function (req, res) {
  res.render('singleItem');
});

Upon running the code, I encountered the following error:

Error: Failed to lookup view "items" in views directory "C:\Users\Karol\views"
    at Function.render (C:\Users\Karol\node_modules\express\lib\application.js:580:17)
    at ServerResponse.render (C:\Users\Karol\node_modules\express\lib\response.js:1008:7)
    at C:\Users\Karol\Desktop\CB\app.js:27:7
    at Layer.handle [as handle_request] (C:\Users\Karol\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Karol\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Karol\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Karol\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Karol\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Karol\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Karol\node_modules\express\lib\router\index.js:275:10)

When accessing localhost:port/items, the above error message is displayed (replace 'port' with the actual port number).

Answer №1

Encountering an issue with resolving the views path? Make sure to include the path module after initializing express

var express = require('express');
var path = require('path');
var app = express();
var port = 3000;

Additionally, once you have set up the ejs template, add the following code:

app.set('view engine', 'ejs');
app.set('views', path.resolve(__dirname, 'views'));

Answer №2

Modify to :

app.use('/products', productRouter);

productRouter.route('/').get(function (req, res) {
  res.render('products');
});

productRouter.route('/item').get(function (req, res) {
  res.render('singleProduct');
});

to :

productRouter.route('/products/').get(function (req, res) {
  res.render('products');
});

productRouter.route('/products/single').get(function (req, res) {
  res.render('singleProduct');
});

Answer №3

const directoryPath = require('path');

To establish the public directory, use the following code snippet:

app.set('view_engine', 'ejs');
app.set('views', directoryPath.join(__dirname,'/views'))

This code retrieves the project directory and configures the views path accordingly.

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

Discover the largest prime number and display it using JavaScript

Currently learning about node.js and faced with an interesting challenge - Create a program to identify and display the largest prime number that is less than or equal to N. Input // Output - 13 // 13 126 // 113 26 // 23 During my previous course with ...

I am attempting to gather outcomes from two separate arrays

I have a challenge of filtering the first array based on the text in the second array. I am trying to figure out how to update the count filter in the first array using values from the second array. First Array: var firstArray =[{text:"India",co ...

Utilizing conditional statements for confirming purchased orders with a pop-up confirmation box

function purchaseClicked() { var orders = prompt("Are you sure you want to buy these Items?"); if (orders != null) { alert('Please try selecting your items again!') } else { alert('Thank you for shopping ...

What is the best way to selectively adjust object parameters in unit testing?

In my module, I have an object with several parameters. I want to rewire only specific parameters of this object. Here is a snippet from my 'module.js' file: var obj = { param_A: 'valueA', param_B: 'valueB', param_C: &a ...

Verify if Angular 2 route parameters have a legitimate value

Within an angular2 component, I have the following code: ngOnInit() { this.route.params .switchMap((params: Params) => this.elementsService.getElement(+params['id'])) .subscribe(element => { this.elementToEd ...

Generate a series of buttons with generic identifiers that can be easily targeted using getElementById. The IDs will be dynamically assigned

I am looking to dynamically generate unique IDs for a list of buttons, allowing me to easily target specific buttons using getElementById. Here is an example code snippet where each button has the same ID: @foreach (var cat in Model) { <div clas ...

Tips for effectively redirecting traffic to another website

Is there a way to redirect someone from a page URL like example.com/2458/233 to example2.com/2458/233? The first URL contains only a file that redirects to the other domain. Can anybody provide instructions on how to achieve this process? To clarify furt ...

Vuelidate allows for validation to occur upon clicking a button, rather than waiting for the field

As I navigate my way through learning vuelidate, everything seems to be going smoothly, except for one thing. I can't figure out how to trigger validation only when the "Submit" button is clicked. Currently, the fields turn red as soon as I start typi ...

Ways to specifically load a script for Firefox browsers

How can I load a script file specifically for FireFox? For example: <script src="js/script.js"></script> <script src="js/scriptFF.js"></script> - is this only for Firefox?? UPDATE This is how I did it: <script> if($. ...

unusual ejs syntax glitch

After starting to learn node.js and following a blog for practice, I encountered some unexpected issues when trying to render a view as instructed in the blog. I chose ejs as the view engine in express and created a file named signup.ejs with the followin ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

Modifying JavaScript prototypes on the fly can lead to troublesome issues

My curiosity has been piqued by the concept of dynamically changing a constructor's prototype in JavaScript, leading me to the findings above. It appears that an already constructed instance does not inherit the properties of the newly changed protot ...

What is the method for initiating a POST request in Java Script without including any data?

Currently, I am utilizing Ajax to send an array to the router, as demonstrated below... var send = function () { var data = search console.log(data) $.ajax({ type: 'post', url: ...

Communicating between iframes and parent elements via events

I'm trying to trigger an event in my iframe using the following code: $('body').trigger('my_event'); However, I want to bind this event on my main page that contains the iframe like this: $('iframe').find('body&ap ...

Content is cleared from the leaflet popup upon first closure

In my application, I've been working extensively with Leaflet and have a good grasp on the "leaflet way" of doing things. Since I have a single static layout for all my markers, I decided to create a simple Mustache template to insert variable data a ...

Having trouble redirecting to the Google login screen with Passport Google Auth 2.0

Greetings, I have encountered an issue with my server setup. I am attempting to redirect users to the Google authentication screen when they navigate to the /auth/google path. However, instead of being redirected, I am consistently landing on my 404 error ...

Having trouble executing multiple file uploads with node.js resulting in an ERR_EMPTY_RESPONSE?

Currently, I am attempting to upload multiple files on FTP using node.js. Everything seems to be going smoothly as the files are successfully uploaded to the server location. However, after some time passes, I do not receive a success message. Instead, I e ...

DirectionsLight isn't functioning properly in Three.js

I attempted to add lighting in Three.js, but after updating the display, the light didn't seem to affect my cylinder. I simply copied and pasted the source code from the Three.js documentation Three.js as instructed, but to no avail. Below is the cod ...

What is the sequence of Javascript Execution for the event of window.location.href?

After browsing through this discussion on asynchronous JavaScript location.href call and watching a video explaining the event loop, I found no clear explanation regarding the behavior of href within window.location: The script order in the source code is ...

Is there a way to print the full page including scroll tab content?

https://i.sstatic.net/FJt7P.png I am facing an issue where I want to print the entire page including the scrollable content within a tab. Currently, only the visible screen content is being printed. ...