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

Is it possible to verify the creation of a new account through the Okta Authentication API?

I am interested in utilizing Okta to securely store my users' credentials, but I also need to keep additional information such as age, birthday, graduation date, interests, etc. in my MongoDB database. Since the Okta API does not handle this extra da ...

Change the color of a c3js chart when it loads

I have been searching for a way to customize the color of a scatter chart's plot, and I came across an example that uses d3 code within the chart http://jsfiddle.net/ot19Lyt8/9/ onmouseover: function (d) { d3.select(d3.selectAll("circle ...

Live Update Google Sheet Data to JSON Without Reloading Web Page

This particular function is executing smoothly. My main concern lies in updating a DOM element without reloading the webpage, if any alterations are made to the data on a Google sheet I am utilizing a JSON file from Google sheets: https://spreadsheets.g ...

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

Managing active dropdown menus in VueJS

I'm having trouble figuring out why my navigation menu and method to open subitems on click are not working correctly. [![dropdown_menu][1]][1] new Vue({ el: '#app', data: { //menu "menu_title": "a", "child_ro ...

Tampermonkey only allows jQuery Click to execute once within a for loop

Attempting to switch the content of a text area to different cars and then trigger a button click to perform an action, repeating this process for each car until all cars have been processed. var index; var cars = ["car1", "car2", "car3"]; var x = documen ...

AddThis plugin in Wordpress is unresponsive when used with a theme that relies heavily

I've been struggling to properly set up the AddThis Wordpress plugin to display share buttons below each post in an AJAX theme. After inserting this code into the custom button field on the settings page: <div class="addthis_toolbox addthis_defa ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

Navigating Vue 3's slot attributes: A step-by-step guide

Currently, I am facing an issue with a Vue component named MediaVisual. This component contains a slot. The problem arises when attempting to retrieve the src attribute of the slot element that is passed in. Surprisingly, this.$slots.default shows up as u ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

I am attempting to separate this "for" loop in order to generate five distinct DIV elements

Hello there! I am a beginner and I am attempting to create 5 different players by using some code that I found. Here is the code I have been working with: https://codepen.io/katzkode/pen/ZbxYYG My goal is to divide the loop below into 5 separate divs for ...

Is anyone else experiencing issues with loading a font from a CDN? It works perfectly fine on Chrome Browser and Safari for iOS Simulator, but for some reason, it's not loading

It's driving me a bit crazy as I'm not sure where I've gone wrong. I'm currently working with NextJS and have loaded this font into my <Link />. While it displays perfectly on Chrome and Safari in the iOS simulator, it fails to l ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

Insert HTML elements into nested CSS classes

My goal is to utilize jQuery for looping through classes and adding text to an HTML element. I am currently working with the following example HTML: <div class="question"> <div class="title"> <strong>Here's the question ...

Tips for integrating Material UI with Gatsby site generator

I'm diving deep into React by setting up the Gatsby kit with this site generator and Material UI framework. However, I encountered an error that says: Cannot read property 'prepareStyles' of undefined at RaisedButton.render I initiall ...

Confirm the data within an HTML table and apply color coding to the cells appropriately

Currently, I have an HTML table used to automatically validate data collected from soil pollutants analyses. Here is a snippet describing the table structure: <table id="table1"> <thead class="fixedHeader"> <tr><input type="submit" ...