代码之家  ›  专栏  ›  技术社区  ›  Atif Rizwan

调用节点。使用AJAX的独立HTML文件的js API

  •  0
  • Atif Rizwan  · 技术社区  · 2 年前

    Chrome API Tester 但是当我使用AJAX从HTML文件调用API时,它不起作用。 下面是登录用户的示例API。

    app.post('/loginuser', async (req, res) => {
    var query = 'select id,user_pw from t_user where id=?'
    rows = await selectQuery(query, [req.query.id])
    res.status(200).send({'result': rows})
    });
    

    当我用API tester调用这个API时 user_id password req.query.user_id req.query.password req.query 为空。

    http://localhost:8081/loginuser?id=userid001&pw=123

    使用Ajax从HTML文件调用:

    <script type="text/javascript">
            $('#btnSubmit').click(function(){
                var email = $('#txtEmail').val()
                var password = $('#txtPassword').val()
                if(email == "" || password == ""){
                    alert("Please Enter Id and Password")
                    return
                }
                url = "http://localhost:8081/loginuser"
                $.ajax({
                    data: {
                        id: email,
                        pw: password,
                    },
                    dataType: 'json',
                    type: 'POST',
                    url: url
                }).done(function(data){
                    console.log(data)
    
                });
            });
        </script>
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Phil    2 年前

    你的Express应用程序应该从请求正文中读取参数。。。

    app.post('/loginuser', async (req, res) => {
      const query = "select id, user_pw from t_user where id = ?";
      try {
        const result = await selectQuery(query, [req.body.id]);
        res.json({ result });
      } catch (err) {
        console.error("/loginuser", err);
        res.status(500).send("DB error");
      }
    });
    

    app.use(express.urlencoded()); // handle application/x-www-form-urlencoded
    app.use(express.json());       // handle application/json
    

    必须 发送URL查询参数,需要将其编码到jQuery使用的URL中

    // only adding `id` since you're not using `pw` anyway
    const params = new URLSearchParams({ id: email });
    $.ajax({
      url: `http://localhost:8081/loginuser?${params}`,
      method: "post",
      dataType: "json"
    }).done(console.log);