pheromix
pheromix

Reputation: 19287

How to deal with the parameter of a route?

I configured some routes :

var express = require('express');
var router = express.Router();

router.post('/isAccessible/:orgaId', function(req, res, next) {
    res.send("------ param = "+orgaId);
});

module.exports = router;

Then inside an ejs file :

<script>
  function isOrganisationAccessible(orgaId) {
    $.ajax({
      url: "/organisation/isAccessible/"+orgaId,
      type: "POST",
      dataType: "text",
      success : function(data, status, xhr) {
        return data;
      },
      error : function(xhr, status, error) {
        return "";
      }
    });
  }
  $(document).ready(function() {
    alert("test = "+isOrganisationAccessible("xxx"));
  });
</script>

At runtime I get undefined ! So how to retrieve the parameter passed to the route ?

Upvotes: 0

Views: 43

Answers (2)

t.888
t.888

Reputation: 3902

It looks like the issue you're having is that isOrganisationAccessible is asyncronous. Returning the data from the success function is not having the result you're expecting because the data is not returned from isOrganisationAccessible, only from the success function. isOrganisationAccessible will always return undefined.

You can address this by using a promise:

function isOrganisationAccessible(orgaId) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/organisation/isAccessible/"+orgaId,
      type: "POST",
      dataType: "text",
      success : function(data, status, xhr) {
        resolve(data);
      },
      error : function(xhr, status, error) {
        reject(error);
      }
    });
  })
}

Then resolve the promise to check the result:

$(document).ready(function() {
  isOrganisationAccessible("xxx").then((data) => {
    alert(data)
  })
})

Upvotes: 1

Anshul Jindal
Anshul Jindal

Reputation: 388

You cannot access orgaId directly. You need to access it like this :

req.params.orgaId 

update: I tested this simple app and it is working fine on /isAccessible/abc I tested with the get query but with post also it should be fine. Also, why are you using post when you are not sending any data?

const express = require('express');  

let app = express();  

// Function to handle the root path
app.get('/isAccessible/:orgaId', function(req, res, next) {
    res.send("------ param = "+req.params.orgaId);
});

let server = app.listen(3000, function() {  
    console.log('Server is listening on port 3000')
});

Upvotes: 1

Related Questions