0

I am using angular to call into a node get api. "undefined" is being received by node for req.query.reqdata Am I supposed to parse the JSON on the server side? Any help will be greatly appreciated.

Client:

function playOrError(instrument, octave, scaletype, basenote) {
       var reqdata = {
        "instrument" : instrument,
        "octave" : octave,
        "scaletype" : scaletype,
        "basenote": basenote
        };

       $http.get("/api/getfile", reqdata)
      .then(
        function(response) {
          console.log("File request: " + response.data);
        },
        function(error) {
          console.log("File request failed: " + error);
        });
    }

Server:

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
   extended: true
}));

...
app.get('/api/getfile', function(req, res, next) {
  console.log(req.reqdata) 
  var instument = req.query.instrument
  console.log(instrument)

})
  • Might try $http.get(url, {reqdata: reqdata}) – Bennett Adams May 24 '16 at 00:09
  • Tried $http.get(url, {reqdata: reqdata}) server is still logging {} – Impostor Syndrome May 24 '16 at 01:10
  • 1
    Sorry, was on mobile before. If you are trying to pass an object with your request, it's more appropriate to issue a `POST` request with the `{ reqdata: reqdata }` object, and then call on the object on the server side with `req.body.reqdata`. See [this previous SO answer](http://stackoverflow.com/questions/978061/http-get-with-request-body) on the HTTP spec regarding `GET` requests. – Bennett Adams May 24 '16 at 01:45
  • Thanks Bennett, see my answer below. – Impostor Syndrome May 25 '16 at 15:49

2 Answers2

0

reqdata is only the variable name you are using on the client side, and is never seen by express. Rather, console.log(req.query); should log an object (which is the reqdata object you pass into it); This object should have the values you added to that reqdata object, like so:

{
    "instrument" : instrument,
    "octave" : octave,
    "scaletype" : scaletype,
    "basenote": basenote
}

Then you can get the instrument for example by doing req.query.instrument

This is similar to when you pass a variable into a function. Just because the variable is named something when you pass it as an argument doesn't mean the function will use the same name! In this case, reqdata is passed in as the req.query

AJ Funk
  • 2,374
  • 14
  • 18
0

I figured this one out. Bennett was close, but it needs the first value to be params. This way you can send a whole bunch of query parameters via object notation.

$http.get("/api/getfile", {params : reqdata}) 

I also ended up converting te GET into POST eventually.