Prevent Automatic Redirects When Using POST in Express.js

I'm building a simple web app using Node.js and Express 4, and I want to implement a "follow" feature. While inspecting the Github website, I noticed that it utilizes a form with a follow button which posts to the server to follow a user. This approach seems quite effective because it doesn't require reloading the page, just like in GitHub.

However, I'm having trouble figuring out how to achieve this within Express 4. Whenever I try adding code inside the .post route, it always results in a page reload. In jQuery's ajax method, I believe you can simply return false to prevent any changes to the page while still sending the request. That's exactly what I need for my RESTful API since I want to add the user to the current user's following without relying on jQuery specifically for this function. It would be ideal if I could accomplish this directly in Express, but any assistance is welcome.


views/user.handlebars

<h1>{{user.displayName}}</h1>
<p>@{{user.username}}</p>

<form action="" data-userid="{{user._id}}" method="post">
    <button name="follow" type="submit">Follow</button>
</form>

routes/users.js

app.route('/:username')
    .get(function(req, res) {
        // Fetch :username user from API and load information
        ...
    })
    .post(function(req, res) {
        // Prevent page reload

        ???

        // Add PUT :username user to current user's following array
        ...
    });

Answer №1

You've got the right idea, but if you want to add functionality to your button, you'll need to include a script section in your jade file and use some javascript code to create an onClick event that triggers your ajax method.

If this explanation is unclear, please don't hesitate to reach out for clarification.

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

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 ...

Headers are being removed by Express or React

I currently have a basic setup using React and Express. I am in the process of adding headers to a response, but some are not appearing in the React app. On the Express side... app.post('/api/createpdf', (req, res) => { console.l ...

I am encountering an error with an Unhandled Promise Rejection, but I am unable to determine the reason behind it

const express = require('express'); const cors = require('cors'); const massive = require('massive'); const bodyParser = require('body-parser'); const config = require('../config'); const app = express(); ...

Issue with implementing RESTful API in Node.js using Express

Recently diving into node.js, I've been attempting to utilize REST API but have hit a roadblock. Below is the code snippet I'm currently working with: app.js import express from "express"; import cors from "cors"; import dotenv ...

Issue: ENOENT, unable to locate 'C:UsersAliAppDataRoaming pm'

Upon trying to initialize npm in a fresh Node.js installation, I encountered the following error: Error: ENOENT, stat 'C:\Users\Ali\AppData\Roaming\npm' ...

Denied from being displayed in a frame due to a violation of the Content Security Policy directive by a parent element

I'm in the process of developing a Salesforce app that is displayed within an iframe on a Salesforce page. I am using a node express server to render this page. In order to ensure security compliance, I want the app to only display within the Salesfor ...

Step-by-step guide on installing solely 'devDependencies' with npm

Looking to specifically install only the "devDependencies" from my package.json file, I've attempted various commands with no success. Each command ends up installing both production and development dependencies, which is not what I want. npm install ...

Enhance the performance of node.js when processing data from a massive file

My dilemma lies in the challenge of reading and processing a large file with numerous rows. When dealing with small files under 50kb, everything runs smoothly. However, I am faced with a 15MB file for a programming competition, which serves as a hard input ...

Guide on locating an element inside its parent using Puppeteer

When using cypress, I am able to locate child elements within other elements like this: cy.get('div#Login_form).within(() => { cy.get('input[name="human[email]"]').type('John') cy.get('input[name="human[password]"]&apo ...

Encountering ERR_TOO_MANY_REDIRECTS error while deploying my Next.js app on Cloudways hosting platform

My app's page is displaying ERR_TOO_MANY_REDIRECTS This issue only occurs when the site is hosted on cloudways, as it works fine locally. I have tried various solutions but have been unable to identify the cause of the problem. The URL for the sit ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

TurboRepo initiates the web server and promptly closes down without any issues

I have a turbo-repo set up using pnpm, and I am attempting to launch the React frontend for one of my clients with the following command: npx turbo run start --filter=testclient When executing this command, the output is as follows: • Packages in scope: ...

Tips on Implementing Variables in Jade File Post-Rendering

After logging in, I wanted to display the user's name as a link in my index.jade file, but unfortunately nothing is showing up. I've experimented with both req.body.username and req.session, but neither of them seem to be working correctly. Here ...

The chunk event fails to trigger during an HTTPS request

Experimenting with API calls to Splunk. The curl command executes successfully, returning the expected results. curl -k -v -u admin:password -d 'search=search error | head 10' -d "output_mode=json" https://192.168.50.16:8089/servicesNS/admin ...

Failure occurs when attempting to install pods in an integrated development environment compared to

Currently encountering an issue while attempting to execute a pod update from the terminal within my Integrated VS-code environment on a react-native project. The error message received is as follows: node:internal/modules/cjs/loader:936 throw err; ^ ...

Creating a Docker image for a nodejs application starting from a blank slate

I am relatively new to using Docker and I am looking to create a node-js image completely from scratch. I have done some research online, but most images seem to be based on other node-js images. So far, I have attempted to include the node executables a ...

Error encountered while using JavaScript for waiting in Selenium

When using selenium and phantomjs to submit a form and then navigate back to the previous page, sometimes I encounter a timeout error as shown below: TimeoutError: Waiting for element to be located By(xpath,//div[@id='ContactFormBody']/div/br) W ...

There was an error encountered while using the findOneAndRemove() method: TypeError - it was unable to read the property '_id' of an

I encountered an error 'TypeError: Cannot read property '_id' of undefined' when using the findOneAndRemove() function with the required parameters in MongoDB, even though my database has the attribute '_id'. Interestingly, w ...

What could be causing a bad request error when trying to submit data using a form?

I recently created an API route for user registration that requires fields such as name, email, and password. This route has been tested successfully using Postman, and users are being saved in my MongoDB collection without any issues. However, it seems l ...