【问题标题】:send data to ajax from node server从节点服务器向ajax发送数据
【发布时间】:2020-08-31 15:21:59
【问题描述】:

我需要检查用户输入的令牌是否存在,

我的节点 js 控制器:

const checktoken = async (req, res) => {
    const token = req.body.token

    User.findOne({'token': token }).then((user) => {
        if (user) {
            return res.end("GOOOOD");
        }
        return res.end("Baad");
    })
    .catch((err) => console.log(err))   
}

Ajax 方面:

$(document).ready(function(){
    $('#form').submit(function (e) {
        // e.preventDefault()

        $.ajax({
            type: 'POST',
        url: '/api/token/'
        })
        .done(function(data) {
            alert(data)
        })
        .fail(function(xhr, status, error) {
            console.log("Errrrrrr       " + error);
        })
        .always(function(data){
        });
    })
})

html 表单:

<form class="form-inline search-form"  action ="/api/token" method="POST" id="form">
    <div class="form-group label-floating">
        <input name ="token" id="token" >
    </div>

    <button id="subBut" type ="submit"> Verify  </button>
</form>

问题是我总是得到一个警报(BAD token),无论何时是好的,然后以文本格式打印另一页,结果很好

例如,如果我放好令牌:警报是坏令牌,然后打印另一个页面:好令牌(这意味着节点的结果是好的)AJAX 的问题

【问题讨论】:

  • req.body 中有什么内容?我没有看到您发送令牌的任何地方。另外,你在使用 bodyparser 吗?
  • 假设您使用的是 express,文档会说 If you need to respond with data, instead use methods such as res.send() and res.json().

标签: javascript jquery node.js json ajax


【解决方案1】:

首先,您是双重提交,因为您的form 将提交,而您的ajax 调用也会触发。更改form 上的操作以确保它不会尝试自行发布(或者,您可以在提交处理程序中取消注释e.preventDefault)。此外,您没有在 ajax 调用中包含任何数据:

<form class="form-inline search-form" action ="javascript:void(0)" id="form">
    <div class="form-group label-floating">
        <input name ="token" id="token" >
    </div>

   <button id="subBut" type ="submit"> Verify  </button>
</form>
$(document).ready(function(){
    $('#form').submit(function (e) {
    // e.preventDefault()

        $.ajax({
            type: 'POST',
            contentType: 'application/json',
            url: '/api/token/',
            data: JSON.stringify({ token: $('#token').val() })
        })
        .done(function(data) {
            alert(data)
        })
        .fail(function(xhr, status, error) {
            console.log("Errrrrrr       " + error);
        })
        .always(function(data){
        });
    })
})

您尚未包含您的 Express 设置代码,但这需要 app.use(Express.json()) 或(express.json() 取决于您命名导入的行)以便将正文从 JSON 解析为对象

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 2021-04-08
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多