"Struggling with MeanJs: How do I properly POST data and why aren't the service actions triggering as expected

Seeking guidance on Angular, Express, and MeanJs as a beginner. Looking for assistance in posting data and receiving responses. I'm trying to execute a Complile function to send code from a text box to the server, process it, and get a response. However, unsure how to write the necessary code in lab.client.service.js or other files.
I followed a tutorial at https://www.youtube.com/watch?v=DOqLbJTvCv8&feature=youtu.be

File Structure

  1. lab.client.view.html: Contains a text box bound to an angular object "data.code"

    <textarea ng-model="data.code"></textarea>
    

With two buttons triggering functions:

<div style="margin:12px;">
<button type="button" class="btn btn-primary" ng-click="LabController.compile()">Compile</button>
<button type="button" class="btn btn-primary" ng-click="LabController.compileAndUpload()">Compile & Upload</button>
</div>
  1. lab.client.controller.js: Contains methods to compile code

    'use strict';
    
    angular.module('core').controller('LabController', ['$scope', 'Lab',
    function($scope, Lab) {
        $scope.data = {
            code: ''
        };
    
        this.compile = function() {
                    console.log('User clicked compile', $scope.data.code);
            $scope.message = Lab.compile;
        };
    
        this.compileAndUpload = function() {
                     console.log('User clicked compileAndUpload', $scope.data.code);
             $scope.message = Lab.compileAndUpload;
        };
    }
    ]);
    
  2. lab.client.service.js: Defines HTTP requests

    'use strict';
    
    angular.module('core').factory('Lab', ['$resource', function($resource) {
        console.info("client.service: Working!");
        return $resource('lab', {                           
            compile: {
                method: 'POST',
                url: '/lab/compile'  
            },
            compileAndUpload: {
                method: 'POST',
                url: '/lab/compileAndUpload',               
            }
        });
    }
    ]); 
    
  3. lab.server.routes.js: Defines server routes

    'use strict';
    
    module.exports = function(app) {
    var lab = require('../../app/controllers/lab.server.controller');
    
    // Lab Routes
    app.route('/lab/compile')
        .post(lab.compile);
    
    app.route('/lab/compileAndUpload')
        .post(lab.compileAndUpload);
    };
    
  4. lab.server.controller.js: Handles incoming requests

    'use strict';
    
    var mongoose = require('mongoose'),
    _ = require('lodash');
    
    var response = {
    'message' : 'It works'
    };
    
    exports.compile = function(req, res) {
    var code = req.body.data.code;
    res.jsonp(response);
    };
    
    exports.compileAndUpload = function(req, res) { 
        var code = req.body.data.code; 
    res.jsonp(response);
    };
    

Answer №1

You are facing two issues with the current code:

  1. One of the problems lies in incorrectly defining custom resource actions. Make sure to refer to the argument list. The 2nd argument should be used for default Parameters:

    return $resource('lab', {}, {  // <-- 3rd argument                          
     compile: {                     
        method: 'POST',
        url: '/lab/compile'  
     },
     compileAndUpload: {
        method: 'POST',
        url: '/lab/compileAndUpload',               
     }
    });
    
  2. The second issue is seen in the line $scope.message = Lab.compile, where you are assigning the action instead of invoking it:

    this.compile = function() {
         console.log('User clicked compile', $scope.data.code);       //This message is printed in browser console.
         $scope.message = Lab.compile() // <-- invoke
    };
    
    this.compileAndUpload = function() {
         console.log('User clicked compileAndUpload', $scope.data.code);    //This message is printed in browser console.
         $scope.message = Lab.compileAndUpload();
    };
    

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

Encountering 404 Errors while Attempting to Reach API Endpoint in an Express.js Application Hosted on cPanel

I have a Node.js application running on cPanel, and I'm facing 404 errors when trying to access an API endpoint within my app. Let me provide you with the setup details: Directory Structure: public_html/ server.mjs index.html node_modules ...

Even after installing npm3, the npm -v command continues to display version 2.x.x

As I delve into the world of Angular 2, I learned that it requires npm version 3.x.x. Despite installing npm3 with the command npm install -g npm3, when I check my npm version using npm -v, it still shows as 2.15.8. Strangely, running npm3 -v displays vers ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

Issue: [ERR_PACKAGE_PATH_NOT_EXPORTED]: The specified subpath './lib/rest/RequestHandler' is not exported in /node_modules/eris/package.json

Hi there, I'm completely new to this type of technology. Every time I try to run the 'npm start' command, I encounter the following error: [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/rest/RequestHandler' is not defined ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

Mastering the Twitter npm package: the ultimate guide to using multiple query parameters

After researching a post on Twitter Search API capabilities, I discovered that it is possible to exclude certain types of tweets such as retweets or ones that contain links. You can find the original post here. How can this functionality be implemented us ...

Could it be that express-session is not compatible with express 4.13?

I have followed the setup instructions for express-session as outlined in the documentation, but it seems that my cookie is not being created. According to the documentation, simply setting the request.session value should automatically set the cookie. How ...

Numerous applications within our parse-server ecosystem

Is there a solution available for running multiple applications on a single parse-server? If so, what would be the best approach to transfer existing data from multiple parse servers while ensuring that the IDs and other relationships remain intact? For ...

The MEAN application experienced a sudden crash following a series of queries

Here is my mongoose configuration: mongoose.Promise = global.Promise; mongoose.connect(config.dbhost + config.dbname, function(err){ if(err){ console.log(err); } else { console.log('Connected to the database successfully.'); ...

Store unique elements in an array using MongoDB without any duplicates

I have a scenario where users can add elements to an array of objects. The issue arises when user 1 tries to add the same book multiple times, while user 2 already has it in their list. In this case, User 1 should not be able to add the book at all. Here i ...

Tips for identifying the version of a package that is installed using a package-lock.json file containing lockfileVersion = 3

After upgrading from Node 16 (npm 8) to Node 18 (npm 9), I noticed a difference in the structure of the package-lock.json files. Files generated with npm 8 have a lockfileVersion: 2, while those generated with npm 9 have a lockfileVersion: 3. The changes a ...

What is the best way to address the challenge of managing csrf across multiple tabs in express/nodejs?

I implemented CSRF protection in my nodejs/express application using the following configuration: const app = express(), cookieParser = require('cookie-parser'), session = require('express-session'), csrf = require('cs ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

Upon making the initial post request, axios yielded a 404 error code

function checkStudentGrades(e) { e.preventDefault() setSubject(String(responseProfessor[1])) axios .post(`http://localhost:3001/getNotasAluno/${subject}`, { studentSearch }) .then((response) => { ...

When running "npm start," the process unexpectedly stops before the project is built, and no errors are provided

My application seems to have an issue when I start it using 'npm start'. The build process begins but then stops without displaying any error messages. I've let it run for several hours, but it still hasn't completed the building proce ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

The message indicates that "items" has not been defined

Below is the code snippet: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ name: { type: String, required: true }, email: { type: String, require ...

I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png Below is the code for the login route: router.post("/login", async (req, res) => { try { const user = await ...