Navigating to a different URL in a remoteMethod with Loopback and Express

Can anyone provide any guidance on how to redirect to a URL within a model function or remoteMethod? I've been struggling to find documentation on this. Here is the code snippet for reference:

Model Function (Exposes /catch endpoint)

Form.catch = function (id, data, cb) {
    Form.findById(id, function (err, form) {

      if (form) {
        form.formentries.create({"input": data},
          function(err, result) {
            /*
             Would like to redirect to a url here
             */
            cb(null, "http://google.be");
          });
      } else {
        /*
         console.log(err);
         */
        let error = new Error();
        error.message = 'Form not found';
        error.statusCode = 404;
        cb(error);
      }
    });
    };

    Form.remoteMethod('catch', {
    http: {path: '/catch/:id', verb: 'post'},
    description: "Public endpoint to create form entries",
    accepts: [
      {arg: 'id', type: 'string', http: {source: 'path'}},
      {arg: 'formData', type: 'object', http: {source: 'body'}},
    ],
    returns: {arg: 'Result', type: 'object'}
    });

Answer №1

I stumbled upon a helpful solution here. A remote hook needs to be created in order to access the Express object res. Once you have access to it, you can utilize res.redirect('some url').

Form.afterRemote('catch', (context, remoteMethodOutput, next) => {
  let res = context.res;
  res.redirect('http://google.be');
});

Answer №2

If you retrieve the response object from the HTTP context, you can then pass it as a parameter to a remote method and utilize it directly:

Model.executeRemoteMethod = function (data, response, next) {
    response.redirect('https://hostname.com/path?data=${data}')
};

Model.remoteMethod('executeRemoteMethod', {
    http: {
        path: '/endpoint',
        verb: 'get',
    },
    accepts: [
        {arg: 'data', type: 'string', required: false, http: {source: 'query'}},
        {arg: 'response', type: 'object', http: ctx => { return ctx.res; }},
    ],
    returns: [
        {arg: 'result', type: 'any'}
    ],
});

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

Error occurred during the parsing of an AJAX response

Hello, I am currently exploring the world of JavaScript and jQuery. I recently encountered a situation where I initiated an AJAX call in my code and received an unexpected response. My current challenge revolves around implementing an autocomplete functio ...

Alert displayed at the center of the browser when the value surpasses the specified number

My webpage retrieves SNMP data using PHP and displays it with HTML, color-coding the values. I want to add a pop-up alert when a value exceeds a certain number. I have attempted different jQuery solutions without success. The PHP code to get the value: ...

Sending request results to the client's browser in Node.js - A step-by-step guide

I am struggling with figuring out how to send the results of a 'request' to the client browser. This function is executed on my Node.js server. var request = require("request"); function RedirectReceiver(url, currentState, callback){ ; Send ...

To apply middleware to a specific route in Express.js, target only that route for

My dilemma involves working with files on a specific route. To handle this, I've implemented the formidable middleware. Here's how I'm integrating formidable middleware: app.use(formidableMiddleware()); The issue is that adding this middle ...

Adjusting package.json settings for an npm module

An npm package that I am using has an incorrect file path specified in its package.json. The current configuration is: "main": "./htmldiff.js", However, for it to function correctly, it should be: "main": "./src/html ...

Is there a way to retrieve a value from localStorage and use it to automatically set the selected option in a UL-based dropdown list upon page load

I have implemented a unique UL-based dropdown list that I discovered here (specifically the third model) as the foundation for a role-based selection box for my users. To enhance user experience, I am storing their role selection in localStorage so they do ...

Inline checkbox label with Bootstrap 5 styling

How can I align the checkbox with its label? Example <div class="row g-1 border-bottom p-3"> <div class="col border-end justify-content-center d-flex align-items-center"> <div class="h6 text-sm-center h-25&quo ...

Is it possible for an HTML5 video element to stream m3u files?

Hey there, I'm currently working on integrating a video player using the HTML5 video tag. The content I have is being provided by Brightcove and is in the form of an m3u file. Is it feasible to play this video using the HTML5 video tag? My understand ...

What impact do include statements have on performance?

As I develop a node server, utilizing express and ejs as the templating engine, I've noticed that some of my .ejs files contain 7 to 8 include statements for nested partials. I'm curious whether this approach is resource-intensive or if it won&ap ...

Incorporating multiple CSS style sheets within a single HTML document

As part of my assignment, I have successfully created two different CSS style sheets. The next step is to link both style sheets to a single HTML page and provide users with the option to switch between the two styles. I am wondering how to achieve this. ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

The use of callbacks is ineffective in addressing the asynchronous nature of

Hello everyone, I'm currently working on a weather app and I'm facing an issue with the asynchronous behavior of useState. I've come across some suggestions on Stack Overflow that using a callback in the useState function might solve the pro ...

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

Is it advisable to optimize your SEO by placing the JavaScript code at the bottom of your webpage?

Is this just an urban legend or is it actually true? I've heard that when web crawlers analyze a webpage, they have a time limit to capture all available code (like html) before moving on to the next page. If the JavaScript code is in the head sectio ...

Combine arrays using union or intersection to generate a new array

Seeking a solution in Angular 7 for a problem involving the creation of a function that operates on two arrays of objects. The goal is to generate a third array based on the first and second arrays. The structure of the third array closely resembles the f ...

Utilize Google Calendar Node.js to Retrieve and Display Upcoming Events in Express.js App

As someone who is new to javascript/node.js/express.js, I've been struggling with a particular issue. After following the instructions in the "Google Calendar API Node.js Quickstart", I was able to successfully display a list of upcoming events by run ...

Change the class of each item in a list individually by hovering over them with the mouse using JavaScript

How to toggle classes in a list item one by one using the mouseover event in JavaScript? const items = document.querySelectorAll("ul li"); let currentItem; for (const item of items) { item.addEventListener("mouseover", e => { currentItem &am ...

Return to a mention of a tree reference

Here is an example code snippet: <table> <tr> <td></td> <td></td> <td> <table> <tr> <td><a href="#" class="fav">click me</a></td> ...