What is causing my browser to retrieve JSON response from Express?

Scenario:

I've designed a website that features a form with a POST action. The objective is for users to input their email addresses into the form. Once an email is submitted, a POST request is dispatched to the server. By utilizing Express and the MailChimp API, I'm able to store this email in my MailChimp account through the backend app.js file.

Issue:

Upon successfully adding the email, I respond with a dummy JSON object using res.json(). Currently, this JSON object is just a placeholder, but in the future, it will be used to relay success details. The setback arises when my browser redirects from my index.html to showcase this JSON file. I aim to prevent the page from reloading or redirecting to the JSON response. What am I missing in this setup?

I would greatly appreciate any assistance that can be provided, thank you :)

Methods I've attempted: res.end(), res.send(), and res.sendStatus(200)

APP.JS (for POST operations):

// Signup Route
app.post('/signup', (req, res) => {
    const {email} = req.body;

    console.log(req);

    // Ensure all fields are filled
    if(!email){
        res.redirect('/fail.html');
        return;
    }

    // Create request data
    const data = {
        members: [
            {
                email_address: email,
                status: 'subscribed',
                merge_fields: {} // may consider removing this line....
            }
        ]
    };

    const postData = JSON.stringify(data);

    const options = {
        url: 'myprivateurl',
        method: 'POST',
        headers: {
            Authorization: 'myprivatekey'
        },
        body: postData
    };


    request(options, (err, response, body) => {
        if(err) {
            res.redirect('/fail.html');
        }
        else{
            if(response.statusCode == 200){
                //res.redirect('/success.html');
                console.log("server side success");
                res.json({
                        success: true,
                        message: "Some success message",
                        data: "some data if there's any"
                });
            }
                else{
                        res.redirect('/fail.html');
                }
        }
    });
});

HTML (exclusive to form features):

 <!--Email List-->
            <div id="mailListHolder">
                SIGN UP FOR OUR MAIL LIST!
                <br>

                <div id="successtext"> Thanks! </div>
                <form id="emailform" action="/signup" method="POST">
                    
                    <input name="email" type="text" placeholder="example@email.com" onfocus="this.placeholder = ''"/>
                    <input type="submit" />
                </form>
            </div>

CLIENT JS (pertaining to form functionality):

$('#emailform').submit(function() {

    console.log("emailform submit case WORKING!");
    $("#emailform").css({
        "display": "none",
    });
    $("#successtext").css({
        "display": "block"
    });

    return false;
});

Answer №1

Simple guide for setting up user registration with express :

Creating a new user account

app.post('/api/user',(req,res)=>{
    const user = new User({
        email: req.body.email,
        password: req.body.password
    });

    user.save((err,doc)=>{
        if(err) res.status(400).send(err)
        res.status(200).send(doc)
    })
})

User model definition

const userSchema = mongoose.Schema({
    email:{
        type:String,
        required:true,
        trim:true,
        unique:1
    },
    password:{
        type:String,
        required:true,
        minlength:6
    }
})

const User = mongoose.model('User', userSchema )

If you need further assistance, you can check out: https://github.com/karenaprakash/nodejs-sec-and-auth.git

This project serves as a demonstration for using express.js

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

Inquiry about Tree Traversal in Javascript using Jquery

Consider the following scenario: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>Sub Item</li> </ul> </li> <li>Item 3</li> </ul> This list is dynamically generated by another piec ...

Looking to trigger a PHP page by clicking on a div?

Is there a way to trigger a PHP page call when a user clicks on a <DIV> with AJAX? Additionally, can the text of the DIV be changed to display "LOADING....." simultaneously? I lack knowledge about AJAX. Could you please provide me with more details ...

Retrieving data from a child component that has been added in React

One of the challenges I am facing is dealing with a main react component that dynamically appends child components, like <Child />, on button click The structure of my Child component looks something like this: <form> <input .... /> ...

How can I transfer PHP/MYSQL information into a PDF?

I've recently developed a Student Information Form that is linked to a MYSQL database. Now, I'm looking to export all the collected data from the MYSQL DB into a PDF file. Is there a way to accomplish this task? Any suggestions on how to achieve ...

Issue with Wordpress css rendering on Internet Explorer

My webpage is functioning well in Chrome and Firefox, but I'm facing compatibility issues with Internet Explorer. I've identified several bugs related to tables and layout, however, I'm struggling to resolve the font and text-transform prob ...

Using Console.log() will display 'undefined' prior to receiving any data

I am facing a problem with a lifecycle hook that I have been trying to troubleshoot. export default class EditRevision extends Component { state = { data: [], customColumns: [] } componentWillMount = () => { axios.get('http:/ ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Utilizing Draft JS to dynamically insert text in the form of span

I'm utilizing Draft.js with its mentions plugin. Occasionally, I'd like users to input a mention not by choosing from a dropdown menu, but by typing something like, for example, "@item" or "@item". In the function below, you can observe that if ...

Trigger Vue to scroll an element into view once it becomes visible

I created a dynamic form that calculates 2 values and displays the result card only after all values are filled and submitted, utilizing the v-if directive. Vuetify is my chosen UI framework for this project. This is the approach I took: <template> ...

Combining column values with AngularJS

What is the best way to merge column values in AngularJS? ...

Don't delay in fulfilling and resolving a promise as soon as possible

Currently, I am facing an issue with a downstream API call that is returning a Promise object instead of resolving it immediately. This is how I am making the downstream call: const response = testClient.getSession(sessionId); When I console.log(response ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Transform an object containing key-value pairs into an array of objects that include the key name and its corresponding value

My mind is spinning with this problem... I'm struggling to transform the req.query I receive in Express, which is an object, into an array of objects. I need to pass these to SQL Server as inputs for stored procedures. Here is the data I have - { ...

Redux's 'connect' function fails to recognize changes in the state array

I've recently implemented redux with a reducer that handles an array of time slots for a specific date. Whenever the date is changed, the reducer successfully updates the state (confirmed through console logs in my mapStateToProps function). However, ...

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

Excessive alerts being produced within the loop

I am trying to remove a wine from a JSON wine list and I want to display an alert if the wine doesn't exist in the JSON file. However, the alert is popping up for every entry in the list. I am struggling to find a way to use an if statement before pro ...

Seeking help with a problem regarding the Tooltip Effect not displaying over a button

I'm currently struggling with implementing a tooltip for the "Back-end" button on my webpage. Despite my efforts, the tooltip effect fails to display over the button, and I'm at a loss as to why. Below is the code snippet I am working with: < ...

My eCommerce website is currently experiencing some technical difficulties that need to be addressed

I'm in need of assistance with a particular error I encountered. I was following an ecommerce example application and everything seemed to be going smoothly until I clicked on "Shop Now." At that point, I received the following message: Server Error T ...

Guidelines for validating email input using jQuery

Although I am not utilizing the form tag, you can still achieve form functionality using jQuery Ajax. <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password ...

The backspace key is unresponsive following the use of a jQuery class

Using a specific class for an input field: Here is the code for the input field: <?php echo $this->Form->input('duration', array('class'=>'input-large text-right number-field','value'=>'0&apo ...