Setting up an alert box in a browser using express

Currently, I am utilizing express to dispatch emails using the nodemailer module. Here is a snippet of my code:

app.post('/', (req, res) => {
const output = `
<p>You have a new contact request.</p>
<h3>Contact Details</h3>
<ul>
<li>Name:${req.body.name}</li>
<li>Email:${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;

// setting up the transporter object with SMTP details
let transporter = nodeMailer.createTransport({
    host: "mail.gmail.com",
    port: 587,
    secure: false,
    auth: {
        user: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8094808c8481ad8a8c808481c38e8280">[email protected]</a>',
        pass: '2020'
    },
    tls: {
        rejectUnauthorized: false
    }
});

// sending mail through configured transport
let mailOptions = {
    from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="18756175797174587f79757174367b7775">[email protected]</a>",
    to: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a27332c38232f242e0a2d272b232664292527">[email protected]</a>",
    subject: "the subject",
    html: output
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    
    console.log("Message sent: %s", info.messageId);
    console.log("Preview URL: %s", nodeMailer.getTestMessageUrl(info));
   res.render('index', { msg: 'email has been sent' });
    res.redirect('back');
});});

Upon hitting the submit button, the following code redirects to the Contact page:

        res.redirect('back');

A message is then displayed using this code:

       res.render('index', { msg: 'email has been sent' });

My objective now is to showcase the text in an alert box instead of using the previously mentioned method. I attempted the following approach:

res.render('index','<script>alert("email has been sent")</script>');

Unfortunately, this approach did not work at all. Moreover, I am not implementing ajax. Any thoughts or possible solutions?

Answer №1

Executing a script directly from a server response such as

<script>doSomethingMaybeBad();</script>
may not run smoothly on modern browsers due to potential security risks. It appears that the entire page content <html>...</html> is not being loaded on the client side with these requests.

My suggestion would be to handle ajax responses from the client side and display an alert accordingly. Though without viewing all your code, here's a basic concept:

Replace:

res.render('index','<script>alert("email has been sent")</script>');

with a JSON response, or a response structured similarly to how it was before like this:

{ msg: 'email has been sent', status: 200 }

Then in your client-side code, swap something like this (making an educated guess based on the lack of a client side example provided):

$('msg').html(response.msg)

With:

if (response.status === 200) {
    alert(msg.msg);
    // consider redirecting here if necessary?
} else {
    // show error message, using jQuery in this case but adjust it based on your setup
    $('msg').html(response.msg)
}

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 retrieve local variable JSON arrays using ajax/getJson()?

When starting a project without a database or data source, I often create json arrays in a *.js file to populate screens until the data modeling or database creation is complete. I am trying to figure out how to write an ajax/getJson() function to access ...

What is the best way to convert a JSON object back into an object with its own set of methods?

Currently, I have a JavaScript object with multiple methods attached via prototype. When I serialize the object to JSON, only the property values are saved, which is expected. It wouldn't make sense to save the methods as well. Upon deserialization ...

"Learn the technique of adding a comma after each object and transforming it into an array using JavaScript in React JS

Is there a way to add commas after each object and transform it into an array? Below is the response data: {"url":"example.com/john","age":"32"}{"url":"example.com/mike","age":"42& ...

Eliminate any spaces surrounding the text within the div tag

Is it possible to eliminate extra space at the end of text using CSS (or possibly JS)? I've experimented with various display properties, but none seem to be effective. I need to dynamically insert a blink-div at the conclusion of a multi-line sentenc ...

Attempted to execute a Vuex mutation outside of the designated store handler

Within my program, I have designed a form that consists of two checkboxes and a submit button for demonstration purposes. Upon clicking a checkbox, the selection is saved to a variable, which is then pushed to the vuex store when the submit button is click ...

Enabling a Backbone Model to have multiple pathways

As a newcomer to the world of Backbone, I am in the process of creating a basic API for a website. However, I've encountered a puzzling issue that has me stumped. Within my front end code, there exists a Backbone Model named Item with a urlRoot of "/ ...

JavaScript Stopwatch Break

Below is the code snippet. How can a button be implemented to pause the timer and then resume it when the resume button is pressed? The // marks indicate where I plan to add my pause and resume functionality. Thank you in advance for your assistance! &l ...

Troubleshooting issue: PHP INSERT Prepared statement not working when using AJAX

Currently, I am trying to construct an INSERT statement using AJAX along with a prepared statement in PDO. This is my first attempt at combining AJAX and PDO, so there might be mistakes due to lack of experience. In its current state, I keep encountering ...

What is the best way to incorporate an immediately invoked function expression (IIFE) within the return statement of a React

I currently have a modal that pops up when the user clicks a button on my page and it's functioning perfectly: render() { return ( <div> <section> <button onClick={() => this.refs.simpleDialog.show()}> ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

Using async/await with recursion in NodeJS for handling express requests

My code contains a function named GetAllData() that triggers the GetPurchaseData function, which in turn calls itself recursively until all the data is loaded. async function GetAllData(){ console.log("starting loading purchase data"); await G ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

I'm confused as to why the icon color isn't changing on the Blogger homepage for each individual user

I'm experimenting with changing the eye color based on visitor count. It works perfectly fine on static posts in my Blogger, but it fails to update the eye color properly on my homepage according to the set numeric values. Instead of displaying differ ...

Choose a row in an Angular ngGrid upon loading the page

My question is in relation to this inquiry How can I retrieve selected rows from ng-grid? Check out the plunker sample - http://plnkr.co/edit/DiDitL?p=preview Upon page load, I am looking to have a row pre-selected without relying on 'ngGridEventDa ...

Navigating through paginated data can be made easier by using Backbone.PageableCollection in conjunction with a personalized

I have developed an application that interacts with a database known as LeanCloud. Currently, I have configured a page to display all the users stored in the database. However, LeanCloud has a limitation where only 100 pieces of data can be retrieved per r ...

Strategies for Resolving CORS Problems in Redux React when Using Express and Node

Currently, my React App utilizes React Router and Redux as its primary state manager. On the server side, Express and Node are used to handle requests. Due to limitations with an external service, CORS cannot be enabled. As a result, I must rely on my app ...

angular-routing does not seem to redirect properly

I'm encountering an issue after logging in, as my page is not redirecting to the main page. Upon investigation, I found that the login condition works when using $window.location. However, I want to implement angular-route to restrict access to the ma ...

Is there a way to capture and monitor all page traffic within a scrollable website using playwright?

Here is the code I am using: import { firefox } from 'playwright'; // domain let domain = 'https://www.reddit.com/' // create a new page const page = await browser.newPage(); // set routes await page.route('**', async route = ...

Notification of failed fetch in backbone

We are experiencing a problem with our backbone application. Our goal is to show a notification to the user when a fetch fails (due to timeout or general error). Instead of displaying an error message on a new page, we want to overlay a dialog on top of th ...

PHP script to automatically update a table in a database upon the closure of a

I recently experimented with the following code snippet: <script> function myFunction() { return "You have not logged out of your account. Do you want to leave without logging out? "; } </script > <body onbeforeunload="return myFun ...