The EJS view fails to render when called using the fetch API

Within my client-side JavaScript, I have implemented the following function which is executed upon an onclick event:

function submitForm(event) {
    const data = { name, image_url };

    console.log(data);

    fetch('/', {
        method: 'POST', 
        headers: {
            'Content-Type': 'application/json',         
        },      
        body: JSON.stringify(data),
    });
}

This function sends a POST request to the Express.js backend of the application, invoking another function that should render either of two EJS views. Here is the corresponding Express.js function:

router.post('/', function (req, res) {
    console.log('hitting router post');
    var { name, imageURL } = req.body;
    console.log(name, imageURL);
    if (nicknameIsAvailable(name)) {        
        let user = {
            nickname: name,
            id: '',
            image: imageURL,
        };
        console.log("new user connecting")
        res.cookie('nickname', name, { signed: false });
        res.render('chat', { nickname: name });
    } else {
        console.log('rejecting user ' + name + ' as it is already taken');
        res.render('index', { message: userTakenErrorMessage });
    }
});

The issue here lies in the fact that res.render does not directly render the EJS view. It seems to be returning the HTML markup of the view to the client-side JavaScript instead. To achieve the desired behavior of rendering the "chat" or "index" views with the given arguments, how can this be addressed?

If this specific approach does not yield the intended results, what alternative methods could be explored to add data to the body of a request without relying on a form and then triggering the rendering of a view?

Answer №1

An ajax call has been made, and the rendered HTML will be received within the resolved promise of the fetch function. To show the response content, follow this code snippet:

fetch(...).then(res => res.text()).then(htmlStr => {
  document.open();
  document.write(htmlStr);
  document.close();
})

Answer №2

Experimenting with various methods like fetch() and XMLHttpRequest(), it became apparent that while the server successfully transmits data for rendering, the actual rendering process is not initiated.

After much trial and error, the solution that finally worked was utilizing window.location.href = followed by the URL of the page. The example below illustrates this process:

Client side:

window.location.href = `booksinfo/${bookId}`

Server side:

app.get("/booksinfo/:id", (req, res) => {
  res.render("singlebook.ejs")  
});

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

Too many redirected times occurred while trying to authenticate on localhost using Express.js

Recently, I implemented a function to verify whether a user is authenticated or not. Here is what the code looks like: app.use(compression({threshold:1})); app.use(logger('dev')); app.use(session({ secret:'node.js app', resave:fa ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

Search for a result based on a connection, but ensure that the association is not included in the final outcome when using

Basically, I'm trying to search for something in a table using the method include: [{ model, where }], but without actually including the model itself. I have two models, Part and Set, with a one-to-many connection. I am looking for Parts that are re ...

What is the best way to create a series of synchronous HTTP requests using $http in AngularJS?

I am facing the challenge of uploading a list of video objects with different attributes and links. Currently, I have set up a loop to go through each object in the list and upload the videos one by one since the service I am using does not support multipl ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Ajax request missing Github Basic OAuth token in authentication process

My personal access token is not being passed to the request when I make an ajax call. I keep receiving an error message saying API rate limit exceeded for 94.143.188.0. (But here's the good news: Authenticated requests get a higher rate limit.. I atte ...

I'm curious, in which environment does SvelteKit, Next.js, and Nuxt.js code execute? Also, is it possible to create HTTP request handlers within

My experience with using SvelteKit in my personal projects has been quite enjoyable. However, coming from a background of working with frameworks like Next.js and Nuxt.js, I often find myself confused about where the code I write actually runs. In my day ...

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

Uncertainties surrounding the use of JSON data versus a JavaScript object

As a newcomer to programming, I have ventured into Stack Overflow and W3schools to enhance my skills. Recently, I created a small project for educational purposes. One dilemma is bothering me - is the JSON file I generated actually in proper JSON format o ...

I am curious about the functionality of sessionStore.close() in the `express-mysql-session` package

It's not entirely clear what the purpose of this operation is, as per the documentation. Closing the session store To properly close the session store: sessionStore.close(); What does it mean to actually close the session store? For example, all ...

What sets apart a space after the ampersand from no space in Material UI?

Could you clarify the difference between using a space after the ampersand compared to not having a space? For example: Why is there a space after the ampersand in & label.Mui-focused but no space in &.Mui-focused fieldset? const WhiteBorderTextF ...

Why won't my controller function fire with ng-click in AngularJS?

I'm having trouble getting a function to execute when my button is clicked. Despite the fact that this code appears correct, the function defined in my controller isn't being triggered. The code compiles without errors as shown in the console. A ...

The namespace does not have any exported object named 'LocationState'

I encountered the following issue while attempting to execute my TypeScript application: Namespace '"C:/DevTools/git/motor.ui/node_modules/history/index"' has no exported member 'LocationState'. Here is a snippet from my pack ...

Disable form input fields while keeping all other elements enabled

Currently, I am facing a dilemma where I must deactivate specific input fields within a form. Given that there are numerous fields to consider, individually disabling each one seems impractical. Can anyone offer advice on how to disable a set of elements ...

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

What is the best way to include a dialog div within a form tag?

I am facing an issue with a JQuery dialog on my webpage. The data entered into the dialog seems to get lost because the dialog is placed outside the form tag. Here is how it appears: https://i.stack.imgur.com/fnb07.png So far, I have attempted this soluti ...

Clicking on a specific month results in displaying only one row from the database rather than showing all rows associated with that particular month

I am facing an issue with my calendar feature on the website. The problem is that when I click on a specific month, it should display all the data associated with that particular month. However, the current code does not seem to work as expected. For insta ...

What is the best way to select an element based on its relationship to another Element object using a selector?

I am currently developing a small library in which I require the ability to select a relative element to the targeted element using the querySelector method. For instance: HTML <div class="target"></div> <div class="relative"></div& ...