Home > Blockchain >  Call Node.js APIs from standalone HTML file uisng AJAX
Call Node.js APIs from standalone HTML file uisng AJAX

Time:07-28

I have created several Node.JS APIs and tested all APIs using Chrome API Tester. But when I call that API from HTML file using AJAX it doesn't work. Here is example API to login user.

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})
});

When I call this API from API tester with user_id and password I can get the parameters from req.query.user_id and req.query.password. But when I call that same API from HTML file, req.query is empty.

Call from API tester: http://localhost:8081/loginuser?id=userid001&pw=123

Call From HTML file using Ajax:

<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>

CodePudding user response:

Sending credentials via URL query parameters is generally a very bad idea.

Your Express app should read parameters from the request body...

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");
  }
});

Make sure it can handle either urlencoded data (that's what jQuery will send), JSON or both

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

If you absolutely must send URL query parameters, you need to encode them into the URL jQuery uses

// 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);
  • Related