【问题标题】:error message is not displayed asynchronously ajax错误消息未异步显示ajax
【发布时间】:2019-05-22 14:35:37
【问题描述】:

在我的登录/注册表单中,我使用了 jquery ajax 但它不起作用,当用户输入我的 mongo 数据库中不存在的错误信息时,它应该在我的 div 中添加用户未注册的错误消息(无需重新加载当然)但它不是发送我的错误消息,如res.send 方法(在空白页面中)这里是代码

app.post('/login',
async (req, res) => {

    try {
        const { username, password } = req.body;
        const user = await User.findOne({ username, password }).select('-password').lean();
        if (!user) {
            res.status(500).send({error: "user is not registered"});

            return;
        }

        req.session.user = user; 
        res.redirect('/dash')  
        return res.status(200).send('Session ID: ' + req.sessionID);


    }
    catch (error) {
        res.status(500).send(error.message);
    }
});

nodeJS 代码

<body>
<form action="/login" method="POST"> 
    <input type="text" placeholder="username" name="username" id="username"> 
    <input type="password" placeholder="pass" name="password" id="password"> 
    <button type="submit" id="zaza">Login</button>
    <div id="errMsg"></div>
     <br/>
    or <strong><a href="/reg">Sign Up</a></strong>
  </form>
  <script type="text/javascript">

    $('#zaza').on('click', function(event) {
event.preventDefault();
const username = $('#username').val(), password = $('#password').val();

$.ajax({
type: 'POST',
data: { username: username, password: password },
url: 'http://localhost:8080/login',
success: function(sessionID) {
  console.log(sessionID);
},
error: function(xhr, status, err) {
  const errMsg = xhr.responseText; // Your error msg
  $('#errMsg').html(errMsg);
 }
 });
 });

</script>

ajax 代码

【问题讨论】:

    标签: node.js ajax mongoose


    【解决方案1】:

    您不能同时发送重定向和状态消息。

    更好地检测请求是否为 ajax、json 并根据要求以适当的响应进行响应。

    所以这里是修复:

    1) 修复服务器端代码:

    app.post('/login', async (req, res) => {
        try {
            const {username, password} = req.body;
            const user = await User.findOne({username, password}).select('-password').lean();
            if (!user) {
              return res.status(404).send({
                message: 'user is not registered'
              });
            }
    
            req.session.user = user;
    
            const redirectTo = '/dash';
    
            if (
              req.is('json') // request content type is json
              || // or
              req.xhr // is ajax
            ) { 
              // respond with json response
              return res.status(200).status({redirectTo});
            }
    
            // not ajax request 
            // then respond redirect header
            res.redirect(redirectTo);
        }
        catch (error) {
            res.status(500).send({
              message: error.message
            });
        }
    });
    

    2) 修复客户端代码:

    <form id="login" action="/login" method="POST"> 
      <label>
        Username: 
        <input type="text" name="username" value="">
      </label> 
    
      <label>
        Password:
        <input type="password" name="password" value="" autocomplete="off"> 
      </label>
    
      <button type="submit">Login</button>
      <br/>
      <div class="error"></div>
    </form>
    
    <script type="text/javascript">
    $(function() {
    
      var $loginForm = $('form#login');
    
      // handle form submit event
      $loginForm.on('submit', function(e) { 
        e.preventDefault(); // prevent browser doing default post
    
        $.ajax({
          type: $loginForm.attr('method'), // get method from form tag
          url: $loginForm.attr('action'),  // get action url from form tag
          data: $loginForm.serialize(),    // sending url-encoded string from fields
    
          // something went wrong
          error: function(xhr, textStatus, error) {
            try {
              var response = JSON.parse(xhr.responseText); 
              if (response.message) { // if json response has message field
                $loginForm.find('.error:first').html(response.message);
              }
            }
            catch (error) { // tried to parse response string as json, but could not - then just put error string to div
              $loginForm.find('.error:first').html(xhr.responseText);
            }
          },
    
          success: function(response) {
            if (response.redirectTo) {
              window.location.href = response.redirectTo;
            }
          }
        });
    
      });
    
    });
    </script>
    

    参考文献:

    1) jQuery preventDefault

    2)jQuery serializeArray

    3)jQuery $.ajax fields and explanation

    4) ExpressJS detect ajax request

    5)ExpressJS req.is

    【讨论】:

    • 它的代码很好很简单,谢谢,但为什么我们需要 serializeArray?以及更改数据设置的目的是什么
    • serializeArray() 获取表单字段并自动转换为对象,如:{username: 'someone', password: 'some', ...},定义内容类型有助于服务器端正文解析器使用 json 解析器。
    • 请稍等
    • 似乎此代码不起作用,也没有像我发布的图片中那样给我消息,但是当您更新 {"message":"user is not registered"}
    • @codR 您更新了服务器端代码并​​重新启动了吗?您是否更新了 html 表单?你更新了客户端 js 代码了吗?
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2012-06-08
    • 2016-09-29
    • 2018-10-02
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多