$ .ajax POST正在发送数据,但它在服务器的响应中显示为未定义

时间:2018-03-04 02:23:28

标签: javascript ajax express mandrill body-parser

我正在尝试允许从我的网站发送电子邮件。我试图将信息传递给服务器,但是当我在控制台上记录消息时它返回为未定义。我真的不知道如何确定服务器正在获取什么信息,因为我从控制台登录数据的所有尝试都是未定义的。我之前没有使用$ .ajax,我通常使用XMLHttpRequest,我也不知道我是否正确地执行此操作。我想使用$ .ajax。前端代码是:

$(function () {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function ($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function ($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "mail",
                type: "POST",
                datatype: "json",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function () {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function () {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function () {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function (e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function () {
    $('#success').html('');
});

,后端代码为:

var express = require('express');
var mail = express.Router();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var mandrill = require('mandrill-api/mandrill');
var config = require('../mailkey.js');
var mandrill_client = new mandrill.Mandrill(config.key);

mail.post('/mail', jsonParser, function (req, res) {
    var message = {
        "html": "<p>" + req.body.message + "</p>",
        "subject": "*You have received a message from someone*",
        "from_email": config.from,
        "from_name": req.body.name,
        "to": [{
            "email": config.from,
            "name": config.name,
            "type": "to"
        }],
        "headers": {
            "Reply-To": req.body.email
        },
        "metadata": {
            "phone": req.body.phone
        }
    };

    console.log(message);
    var async = false;
    var ip_pool = null;
    var send_at = null;
    mandrill_client.messages.send({ "message": message, "async": async, "ip_pool": ip_pool, "send_at": send_at }, function (result) {
        res.sendStatus(200);
    }, function (e) {
        res.sendStatus(500);
        // Mandrill returns the error as an object with name and message keys
        console.log('An error occurred sending the mail: ' + e.name + ' - ' + e.message);
        // A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
    });
});


module.exports = mail;

2 个答案:

答案 0 :(得分:0)

查看您的ajax调用,没有为您的成功处理程序分配参数。

success: function (response){
console.log(response);
}

答案 1 :(得分:0)

我最终没有使用$ .ajax并使用XMLHttpRequest。为了使它工作,我必须通过以下方式将请求标头设置为json:

xhr.setRequestHeader(“Content-type”,“application / json”);我使用的前端代码更改为:

$(function () {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function ($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function ($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            var xhr = new XMLHttpRequest();
            xhr.open('post', '/mail', true);
            xhr.setRequestHeader("Content-type", "application/json");
            var data = {
                name: name,
                phone: phone,
                email: email,
                message: message
            };
            var jsonData = JSON.stringify(data);
            xhr.send(jsonData);
            xhr.onload = function () {
                var response = xhr.response;
                if (response === "OK") {
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                } else {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                }
            };
        },
        filter: function () {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function (e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function () {
    $('#success').html('');
});