Using express to efficiently redirect from a search form?

As a newcomer to this, my goal is to initiate an external API call after entering a term in a search form and then migrating to a new page displaying the outcomes. Here's what I have accomplished thus far.

const express = require('express');
const request = require('request');
const path = require('path');
const app = express();
const PORT = 3000;
const url =
  'https://www.example.com/api/search_term?query=';

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.listen(PORT, () => {
  console.log(`Example app listening on port ${PORT}!`);
});

app.get('/search', (req, res) => {
  res.render('search', { title: 'Hey', message: 'Hello there!' });
});

app.post('/results', (req, res) => {
  const term = req.body.term;
  request(`${url}term`, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      console.log(body);
    }
  });
});

In my PUG file, all that exists presently is a basic search form. My confusion arose when I considered how to redirect from a get request due to the fact that I'm calling an external API.

The plan is to launch the application, establish the search form as the main page, input a term for searching, and then transition to a second page with the search results.

I'm under the assumption that I must re-direct to another get route to retrieve the outcomes from the initial get route containing the search form.

Answer №1

Is it incorrect for me to assume that I should redirect to another GET route that retrieves the results from the original GET route that contains the search form?

No, you are mistaken.

You actually need two separate routes without any redirections.

  1. The first route will display the HTML form for searching
  2. The second route will process the form data and return the search results in an HTML format

The browser will automatically request the second route because its URL is specified in the `action` attribute of the form.

The line `console.log(body);` should be replaced with a call to `res.render` that includes the search results to be rendered within the template.

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

Activate a CSS class on click using JavaScript

Having a bit of trouble as a beginner with this. Any help would be much appreciated. This is the code in question: HTML: <div class='zone11'> <div class='book11'> <div class='cover11'></d ...

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...

What causes the temporary halt of context execution in the eventloop framework?

Presenting the code immediately: setTimeout(() => console.log("next macro")); /// next macro Promise.resolve().then(() => gen.next()) /// microtask inside, #2 const gen = (function*(){ console.log("Hello"); yield; /// #3 console.log("W ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...

The Discord.js script fails to send embedded messages as intended

Issue with sending embedded messages using Discord.js code Embed code not functioning properly: Error code received: ...

What is the best way to convert a List of objects to JSON using a dynamic variable?

I have a need to serialize a list of objects in a specific way: Imagine I have the following C# class: public class Test { public string Key; public string Value; } List<Test> tests; When I serialize this list (return Json(tests.ToArray()) ...

Attempting to access an HTTP Node server from within an HTTPS environment resulted in an SSL error

I am faced with the challenge of connecting to a socket.io from a React client within a Node server. Both the React client and the location of the Node server (a microservice housed in a separate Docker container alongside a Java container) are operating o ...

Tips for choosing a single row in a table using a checkbox

I need help with a table that has multiple rows and four columns. One column is for checkboxes, while the other three are select boxes set to read-only. I want users to be able to edit only one row at a time by checking the checkbox in the first column. If ...

What are some ways to design unique custom data grid toolbar elements?

I am having trouble syncing my custom toolbar buttons with the imported material data grid toolbar components. I would like them to match in style, specifically applying the material styles to my custom components. However, I have not been able to find a w ...

Leveraging Deferred in conjunction with AJAX

I am facing an issue with a series of JavaScript functions that make database calls using AJAX. I need these functions to finish executing and update variables before moving on to the final function. I have attempted to use jQuery $.when but it is not work ...

How can we start a new session upon signing up using cookie-session and passport.js?

Currently, I have set up a /register router specifically for signing users up. In order to keep things simple right now, I am utilizing cookie-session instead of express-session. However, I've hit a roadblock when it comes to authenticating a user du ...

Is there a way to apply filters to jquery datatables during initialization process?

Is there a way to server-side filter datatable during initialization? I attempted the following code: function tableFilter(arg1, param2, value3) { var searchTable = $("#tblsearch").dataTable({ "bRetrieve": true, "b ...

Capturing all response requests from the main process in Electron: A step-by-step guide

I am looking to retrieve the responses for all requests made in my electron app from the main process. In this image, it shows that the desired response can be found in the Response tab rather than the Headers tab on Chrome Dev Tools. Instead of using a ...

Certain Express.Router() routes fail to execute the middleware function

I'm struggling to understand why my use of express.router() is not triggering the assigned middleware function. I have a large application and am trying to add more endpoints to my path, but for some reason the 9th route loads without executing the fu ...

Sending parameters from one Node.js function to another in separate JavaScript files

I am currently working on passing function responses between two Node.js scripts. Here is my approach. Index.js var express = require('express'); require('./meter'); var app = express(); app.get('/',function(req,res){ ...

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...

Having trouble accessing the inline transform scale with jQuery

I am working on a new feature where I need to extract the inline transform scale value from each list item (li). Below is a demonstration for you to assist me: HTML <div style="color:red;transform:scale(1);">Dummy content</div> JS $(functi ...

An Unexpected Appearance of Special Characters in a Python dictionary created from AWS and transmitted to JavaScript via a Django view

In my quest to gather information about my infrastructure, I am working on constructing a dictionary that can be converted into JSON objects. These objects will then be passed to JavaScript for display purposes. I have experimented with using both json.du ...

Retrieve the value of a field from a Formik form integrated with Material UI

I've been working on a way to disable a checkbox group depending on the selected value of a radio group. I took inspiration from the technique outlined in the final section of the Formik tutorial. Using React context has definitely helped clean up the ...