简体   繁体   中英

Why does my browser loading JSON response from Express?

Context:

I have a website with a form POST action. I want users to input their email into the form. Once and email is submitted, a POST is sent to the server. Using Express and the MailChimp API I save this email to my MailChimp account with the backend app.js file.

Problem:

After successfully adding the email, I send a dummy JSON object using res.json(). For now it is just a dummy JSON object, but in the future I would use it to send success details. The problem is my browser redirects from my index.html to display this JSON file. I don't want the page to reload, or redirect to the JSON response. What am I doing wrong?

would really love any help I could get, thanks :)

I have tried: res.end() and res.send() and res.sendStatus(200)

APP.JS (just POST stuff):

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

    console.log(req);

    // Make sure fields are fillled
    if(!email){
        res.redirect('/fail.html');
        return;
    }

    // Make request data
    const data = {
        members: [
            {
                email_address: email,
                status: 'subscribed',
                merge_fields: {} ///may need to remove 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 (just form stuff):

 <!--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="dopedude@mail.com" onfocus="this.placeholder = ''"/>
                    <input type="submit" />
                </form>
            </div>

CLIENT JS (just form stuff):

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

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

    return false;
});

small example for user registration using express :

new user registration

 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 modal

 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 ) 

or you can refer: https://github.com/karenaprakash/nodejs-sec-and-auth.git

this project is demo for express.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM