weixin_33692284 2015-09-23 20:46 采纳率: 0%
浏览 21

POST上的Ajax发布404

I am trying to send a test email using node.

My server code index.js looks like this:

var http = require("http"),
    express = require('express'),
    nodemailer = require('nodemailer'),
     bodyParser = require('body-parser'),
    app = express();

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));

app.post('/contact', function (req, res) {

    var name = req.body.name;
    var email = req.body.email;
    var message = req.body.message;

    var mailOpts, smtpTrans;

    smtpTrans = nodemailer.createTransport('SMTP', {
        service: 'Gmail',
        auth: {
            user: "email@gmail.com",
            pass: "password"
        }
    });

    mailOpts = {
        from: name + ' <' + email + '>', //grab form data from the request body object
        to: 'cmatsoukis@gmail.com',
        subject: "Website Contact",
        text: message
    };

    smtpTrans.sendMail(mailOpts, function (error, response) {
        //Email not sent
        if (error) {
            res.send(false);
        }
            //Yay!! Email sent
        else {
            res.send(true);
        }
    });

});

app.listen(1337, '127.0.0.2');

This is my ajax code when I submit the form

var form = $("form#contact_form");
form.submit(function () {
    event.preventDefault();

    var name = $('#name').val();
    var email = $('#email').val();
    var msg = $('#message').val();

    var info = {"name" : name, "email": email, "message" : msg} 

    $.ajax({
        url: 'http://127.0.0.2:1337',
        type: 'POST',
        data: JSON.stringify(info),
        contentType: "application/json; charset=utf-8",
        jsonpCallback: 'callback', // this is not relevant to the POST anymore
        //dataType: 'json',
        success: function (data) {
            MailSuccess()
            lightSpeed();

        },
        error: function () {
            MailFail();
        }
    });
});

I am getting the error POST http://127.0.0.2:1337/ 404 (Not Found)

I do not think I have the url correct. I have app.post('/contact', function (req, res) { But I do not this that is correct. And shouldn't I put a file name in the url: 'http://127.0.0.2:1337',?

I believe I have everything else correct. Please let me know.

  • 写回答

1条回答 默认 最新

  • H_MZ 2015-09-23 20:48
    关注

    You've registered a POST handler for '/contact' but you are making the request to '/'.

    Since you haven't told express what to do for '/' it returns a Not Found.

    Make the two paths match.

    评论

报告相同问题?

悬赏问题

  • ¥15 Windows Server2016本地登录失败
  • ¥20 基于MATLAB的TDOA
  • ¥15 为啥输入字体突然变了
  • ¥20 已知坐标,换成MATLAB可以用的数据
  • ¥15 这个python五子棋代码的每一句意思是什么啊
  • ¥15 求一段隐藏代码,隐藏一些内容
  • ¥15 汇川EASY521plc电子凸轮
  • ¥15 C++ 如何判断设置快捷键来实现隐藏/显示窗口
  • ¥15 关于#材料工程#的问题:有没有具有电子阻挡层和空穴阻挡层的电池仿真silvaco代码例子或者其他器件具有阻挡层例子的silvaco代码(最好还有相关文献)
  • ¥60 基于MATLAB的TAOD算法