【问题标题】:Return json data from express to ajax post request从express返回json数据到ajax post请求
【发布时间】:2021-11-29 14:42:01
【问题描述】:

我在使用 ajax 和 express 响应时遇到问题。基本上,我正在尝试向 ajax 帖子发送错误响应:

// authentication failed
return res.json({
    msg: 'Incorrect OTP...'
});
$.post({
        type: 'POST',
        url: 'http://localhost:8080/verifyOTP',
        data: JSON.stringify({
            phone: phone,
            m: m,
            otp: otp,
            withCredentials: true
        }),
        success: function(err) { // hack to get error msg
            console.log(err);
        },
        dataType: "json",
        contentType: "application/json"
    });

我已经用 $.post 尝试了错误方法(没有运气)......并且成功功能也不起作用......

我已经在这里呆了 2 天了:/

我不断被重定向到我工作流程中的上一页。

需要注意的是,这条当前路由有查询参数:http://localhost:8080/verifyOTP?phone=8191291382&m=11fe12adb039dd2abfa254291c985c1a9cc860d29c4c970594f086fd75500360.1633875932641。这可能是重定向的原因???

【问题讨论】:

  • 你是怎么触发这个的?听起来您有<a href=""<button> - 如果是按钮,请更改为<button type='button>`,因为听起来页面正在重新加载,这将通过链接(<a href="">)到相同的默认为<button type='submit'的页面或按钮
  • @freedomn-m 我想我设法修复了..见下文:)

标签: jquery node.js ajax express


【解决方案1】:

我想我找到了答案:

更改onClick -> on('click' ...) 并输入e.preventDefault();

$('#submitOTP').on('click', function(e) {
    e.preventDefault();

    var otp = document.getElementById('otp').value;
    var phone = document.getElementById('phone').innerText;
    var m = document.getElementById('m').innerText;

    $.ajax({
        type: 'POST',
        url: 'http://localhost:8080/verifyOTP',
        data: JSON.stringify({
            phone: phone,
            m: m,
            otp: otp,
            withCredentials: true
        }),
        success: function(err) { // hack to get error msg
            console.log(err);
        },
        dataType: "json",
        contentType: "application/json"
    });
});

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-01-05
    • 2020-01-11
    • 2013-12-20
    相关资源
    最近更新 更多