Creating routes in ExpressJs and rendering pages using Vanilla JavaScript

When I send a request to


app.get("/auth/login", (req, res) => {
  res.sendFile(path.join(__dirname + "/authentication/login.html"));
});

using

fetch("/auth/login", {
      method: "GET"
    });

I'm able to receive the HTML page as a response. However, how can I properly display it on the screen without using document.write? Additionally, should route redirections be handled on the client-side or server-side?

Answer №1

Here's a simple way to achieve this:

let element = document.getElementById("id_element");

element.innerHTML = jsonResponse.key;

Make sure that

jsonResponse.key 

contains the result of your fetched and stringified data.

Answer №2

Seems like you're trying to access a specific route in your web browser. Your browser is equipped to handle rendering it, so simply open up a browser and input the route.

Try accessing: localhost:port/auth/login

Routes designed for rendering pages should not typically be accessed using fetch, axios, or other request libraries unless there is a specific and rare use case for doing so.

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

Different ways to change the value of a variable in an isolated scope using another directive

Utilizing a directive with two modes, edit and preview, multiple times in my codebase. function () { return { restrict: "E", scope : { model : '=' }, [...] controller : function($scope, $el ...

Switch up the color of the following-mouse-div in real-time to perfectly complement the color that lies underneath it

I am trying to create a div that changes color based on the complementary color of whatever is underneath the mouse pointer. I want it to follow the mouse and dynamically adjust its color. This functionality is similar to what Gpick does: https://www.you ...

What is the best way to display several components in a particular location within a parent component using react-native?

I am struggling to position multiple components within a parent component at a specific location determined by some calculations. The calculations for the vertical position seem accurate, but the components are not appearing where they should be. I have ex ...

Tips for managing @ManyToMany relationships in TypeORM

In this scenario, there are two distinct entities known as Article and Classification, linked together by a relationship of @ManyToMany. The main inquiry here is: How can one persist this relationship effectively? The provided code snippets showcase the ...

``After successful implementation of app.get in a Node Express application on Mac OS, encountering

app.get("/test", function(req, res, next) { res.sendFile(__dirname + '/test.html'); }); Seems simple enough, right? When I run this server on my Mac, everything works fine. However, when I try to run it on a PC, my browser shows a "cannot GET" ...

Issue with sharing on Facebook via direct URI

I'm currently working on implementing an FB share button on my website. When a user clicks on the button (which features the FB image), they are redirected to . I am dynamically setting the URL as location.href through JavaScript, and the URL is autom ...

Should you make it a point to specifically address 404 errors in your Express application?

If you visit https://expressjs.com/en/starter/faq.html you will see how to handle 404 errors by inserting the code snippet below all middleware: app.use(function (req, res, next) { res.status(404).send("Sorry can't find that!") }) Interes ...

Is the memory usage of node.js proportional to the number of concurrent requests, or is there a potential memory leak?

Running the following node.js code: var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'}); res.write("Hello"); res.end(); }).listen(8888); Upon starting the server ...

Unable to assign attribute following discovery

Can the attribute of an anchor element that is found using find() be set? I attempted this: $(this).children('a').setAttribute("href","a link"); Although it does locate the anchor element, why am I receiving an error when trying to use setAttr ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

Is it necessary to include a request in the API route handler in Next.js when passing parameters?

In my API route handler, I have a function for handling GET requests: import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest, { params }: { params: { id: string } }) { const { id } = params; try { ...

AngularJS: updating a module

I recently started learning AngularJS and I need some guidance on how to refresh the data in a table within a module (specifically, a list of names and post codes). Below is the script where I am trying to reload the JSON file upon clicking a button: < ...

The feature for favoriting or unfavorite a post is currently not functioning correctly on the frontend (react) side

I have been working on a social media website project for practice, and I successfully implemented the liking and disliking posts feature. However, I encountered an issue where when I like a post and the icon changes to a filled icon, upon refreshing the p ...

How to ensure that the select option is always at the top of the select dropdown list in a React.js application

Within the select dropdown menu, I have included a default option value of "--select--". As it currently appears at the bottom of the list, I would like it to be displayed at the top instead. Can someone please assist me in achieving this? In the sandbox, ...

Troubleshooting: MongoDB/mongoose post save hook does not execute

My current setup involves the following model/schema: const InvitationSchema = new Schema({ inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true}, organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Orga ...

Setting the path for convert in ImageMagick, gm, and express.js - a complete guide

Looking for help with resizing uploaded images using gm in an express.js project. Imagemagick and gm are installed and configured, yet encountering an error: { [Error: Command failed: Invalid Parameter - -resize ] code: 4, signal: null } Similar error fou ...

Guide to acquiring and transmitting variables in Node.js

Can anyone guide me on how to pass variables in Node.js? While attempting to fetch and pass some variables to ejs, I encountered the following error: 27| <div id="content"> >> 29| <%=json%> 30| ...

Dynamically fetching and uploading files from a specific path using Node.js, Express, and Angular 1.x

How can I upload or move all files from a specific folder using NodeJS, Express, and Angular 1.x by providing the folder path? What is the best way to handle this operation in either Angular or Node? Should I use: var fs = require('fs') module ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing. lib/routes/getPages const routes = require('next-routes')(); const getEntries = require('../helpers/getEntries'); module.exports = async ...