Call Node.js APIs from standalone HTML file uisng AJAX

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.'/loginuser', async (req, res) => {
var query = 'select id,user_pw from t_user where id=?'
rows = await selectQuery(query, [])
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:

Call From HTML file using Ajax:

<script type="text/javascript">
            var email = $('#txtEmail').val()
            var password = $('#txtPassword').val()
            if(email == "" || password == ""){
                alert("Please Enter Id and Password")
            url = "http://localhost:8081/loginuser"
                data: {
                    id: email,
                    pw: password,
                dataType: 'json',
                type: 'POST',
                url: url


>Solution :

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

Your Express app should read parameters from the request body…'/loginuser', async (req, res) => {
  const query = "select id, user_pw from t_user where id = ?";
  try {
    const result = await selectQuery(query, []);
    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 });
  url: `http://localhost:8081/loginuser?${params}`,
  method: "post",
  dataType: "json"

Leave a Reply