Difficulty with SailsJS Transmitting Information to View Template

I've been trying to establish a connection for hours but haven't had any luck.

All I want to do is transfer some data from a controller to a view template. When I navigate the route without specifying a view template, the browser displays the data in JSON format (confirming that the MYSQL connection is functioning).

However, every time I attempt to link to MYSLQ data (or any data from the controller to the view) to pass it to the template, Sails throws an error stating that the data cannot be found (even though it's visible when returning the JSON data). I suspect this issue may be related to how SailsJS attempts to connect with the EJS template engine or if there's a breakdown between the Model, Controller, and View on the backend?

Below is a simple example that isn't working, yet my ultimate goal is to connect to a MYSQL list of data:

Declaration in Routes.js:

'GET /schools': { view: 'schools/index', controller: "SchoolsController", action:"index"},

SchoolsController.js:

module.exports = {
 index: function(req, res){
    // Just sending this to the view
    res.view({
        "name": "Iparra"
    })
 }
};

index.ejs template:

<div id="theschools">
 <h1>List of Schools</h1>
  <%= name %>
</div>

Error received from Sails.js:

{
    "stack": "ReferenceError: /Users/mnelson/Documents/Mike Files 2/Personal/MyDesign Musings/sails/test-project/views/schools/index.ejs:7\n    5|       <h1>List of Schools</h1>\n    6| \n >> 7|     <%= name %>\n    8| \n    9| </div>\n    10| \n\nname is not defined\n    at eval (eval at <anonymous> (/usr/local/lib/node_modules/sails/node_modules/ejs-locals/node_modules/ejs/lib/ejs.js:237:14), <anonymous>:30:109)\n [truncated]",
  "message": " /Users/mnelson/Documents/Mike Files 2/Personal/My Design Musings/sails/test-project/views/schools/index.ejs:7\n    5|       <h1>List of Schools</h1>\n    6| \n >> 7|     <%= name %>\n    8| \n    9| </div>\n    10| \n\nname is not defined",
  "path": "/Users/mnelson/Documents/Mike Files 2/Personal/My Design Musings/sails/test-project/views/schools/index.ejs"
}

Answer №1

The problem lies in the configuration of your routes. You should remove view: 'schools/index' from

'GET /schools': { view: 'schools/index', controller: "SchoolsController", action:"index"},

Alternatively, you can modify it to

'GET /schools': { 'SchoolsController.index' },

What's the reason behind this adjustment?

Routes need to define either the controller action to be executed or the view to be displayed (if it's a static page).

res.view accepts an optional view path as its first argument (relative to views/). If this argument is not provided, it will default to rendering the

<controllerName>/<actionName>
view.

Answer №2

After delving into the documentation and studying various examples on Github, I finally managed to figure it out. While Sujan pointed me in the right direction, his solution didn't quite resolve the issue. The data was being retrieved, but it wasn't being properly connected to the view. After making some adjustments, I was able to fetch the complete list of data. I had to explicitly return to the view along with the data. Although this method might not be typical in Sails, it was what ultimately made it function correctly. It seems like this should be handled by the route, but that's not the case.

Controller File:

module.exports = {
    index: function(req, res){
      Schools.find().exec(function afterFind(err, schools) {
        if (err) return res.serverError(err);
        console.log(schools);
        return res.view('schools/index', {
          theschools: schools
        });
      });
    }
};

Route File:

'GET /schools': {controller: 'SchoolsController', action:'index'},

I also needed to update the blueprints.js file in config to remove the limit on the find method.

defaultLimit: Number.MAX_VALUE

In addition, I switched the template engine to pug. Here is the updated view file, index.pug

extends ../layout

block body
  #theschools
    h1
    | List of Schools
  p
  table.table
    tr
      th ID
      th Name
      th City
      th Country
    each school in theschools
      tr
        td= school.SID
        td= school.schoolName
        td= school.schoolCity
        td= school.schoolCountry

By examining the response to a similar question on Stackoverflow, I was able to streamline the controller logic and eliminate the need for an explicit view declaration. Custom view/action/controller not working in Sails JS

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

Customizing the language parameter for the apply button script on LinkedIn

Our company's website features the AWLI button which allows users to apply for jobs using their LinkedIn profile. <div name="widget-holder"> <script type="text/javascript" src="https://www.linkedin.com/mj ...

Updating the state in a React array of objects can be achieved by checking if the specific id already exists in the array. If

In the scenario where the parent component receives an object from the child component via a callback function, I need to verify the existence of an object with a specific rowID. If it exists, the object should be updated with the passed value "val"; oth ...

The current environment does not recognize the term 'ScriptManager'

After attempting to solve a JavaScript issue following an AJAX postback in ASP.Net by implementing some code, I encountered an unexpected error during the build process: An unexpected error occurred: The name 'ScriptManager' does not exist in th ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...

Guide on displaying the AJAX response within an HTML or JSP element pulled from a database

description of image 1description of image 2How can I display an AJAX response from a database (map) on a JSP screen? I am able to retrieve the response in the browser console but unsure how to visually render it on the JSP page, like in a table or any ot ...

Painting Magic: Exploring the World of Canvas Zoom and Moves

I'm having trouble implementing zoom and pan functionality for this particular canvas drawing. While there are examples available for images, my case is different since I am not working with images. Any tips or suggestions on which libraries to use wo ...

Dividing a string yields varying outcomes when stored in a variable compared to when it is displayed using console.log()

When the `$location` changes, a simple function is executed as shown below. The issue arises when the assignment of `$location.path().split("/")` returns `["browser"]` for `$location.path() == "/browser"`, but when run directly inside the `console.log`, ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...

The issue of PHP MySQL bind variable not functioning properly with REGEXP_INSTR

My database is currently running on MySQL version 10.1.19-MariaDB, with PHP version 7.0.13. In the database, there exists a table named words2: CREATE TABLE words2 (word varchar(64)); INSERT INTO words2 VALUES ('ABSCESS'), ('ABSCISE'), ...

When I incorporate Express into my React project, I encounter an error stating that the prototype

After attempting to set up a basic React project that connects to a MySQL database, I encountered an error. When requiring 'express' and rebuilding the project, I received the following message when trying to open it in the browser: "Uncaught Ty ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Implement a menu that can be scrolled through, but disable the ability to scroll on the body of the website

When viewed on a small screen, my website transforms its menu into a hamburger button. Clicking the button toggles a sidebar displaying a stacked version of the menu on top of the normal website (position: fixed; z-index: 5;). This sidebar also triggers a ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

Determine the available time slots for reserving a resource

I am developing an application that displays the weekly availability (Monday-Sunday) of a bookable resource. Next to this calendar view, users can select: A) Length of desired booking slot (15 min/30 min/60 min) B) Time zone The time slots are based ...

Tips for setting up a system where PHP serves as the backend and Angular acts as the

I am working on a project that utilizes Angular as the front end and PHP as the back end. Both are installed in separate domains, with the PHP project fully completed and operational. I have created an API in PHP which I plan to call from Angular. My ques ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Sveltejs template not displaying on M1 MacBook Air after running - stuck on blank screen

Currently, I am in the process of learning Sveltejs and have been utilizing for the tutorial, which has been quite effective. However, I decided to work on developing and testing Sveltejs applications locally on my MacBook Air M1. I downloaded the provid ...

The most effective way to initiate an action following a popup

Here's a button that triggers the opening of a popup: <button type="button" id="btnBuscarCuenta" onClick="javascript:AbrirPopUpBusqueda('id_AyudaCuentas', 'pop_cuentas_contables.cfm','', '900px&a ...