使用nodejs后端回复Ajax发布请求

时间:2019-05-27 15:37:27

标签: node.js ajax forms post

我正在尝试使用jquery和ajax在我的网站上创建表单。 在后端,我已经安装了Express。 当我向/ mail发出发帖请求并且一切正常时,我想将json发送回联系页面。我该怎么办?

我已经建立了前端和后端,但是我不知道如何将成功状态或类似的状态发送到前端。

这是我的服务器脚本:

const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
const bodyParser = require("body-parser");

//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/contact.html");
});
app.post("/mail", (req, res) => {
  //here i want to respond with success or error to the front end

});
app.get("*", (req, res) => {
  res.send("hello");
});



app.listen(port, () => console.log(`listening on http://localhost:${port}`));

这是我的前端脚本:

$(function() {

    // Get the form.
    var form = $('#contact-form');

    // Get the messages div.
    var formMessages = $('.form-messege');

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        e.preventDefault();

        // Serialize the form data.
        var formData = $(form).serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // Set the message text.
            $(formMessages).text(response);

            // Clear the form.
            $('#contact-form input,#contact-form textarea').val('');
        })
        .fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });
    });

});

我如何在ajax请求中初始化fail或done函数?

0 个答案:

没有答案