1

I have a very simple Node JS file:

test.js

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('5');
}).listen(process.env.PORT);  

I am calling this file with a very simple AJAX request from a normal JavaScript file:

getData.js

function testNode(){

 $.get("https://mywebsite.com/test.js?q=Person").done(function(data) {
       $.when(data).then(function() {
           console.log(data);
       });
   });
}

The testNode function as it stands will return that hard coded '5' variable. I'd like to instead have it return the 'Person' string that was in the url of the ajax request.

The person running the IIS server node runs on tells me that Express is installed, yet when I add

var express = require('express'); 

On line two, the application breaks and I get a 500 error.

I have only been working with node a few days, but this is the last piece of the puzzle I need to meet my needs. What am I missing?

I have tried req.query.q and req.params('q') but neither have worked.

Marcel Marino
  • 962
  • 3
  • 17
  • 34
  • 1
    If you get Express working, have a look at https://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js – Jonas Wilms Jun 06 '17 at 19:03
  • See [this](https://expressjs.com/en/4x/api.html#app) for a quick Express startup setup – gdostie Jun 06 '17 at 19:05
  • Does express need to be added to the webconfig to work? What other reason would there be for it to break just from including it as a requirement? – Marcel Marino Jun 06 '17 at 20:09
  • @Jonasw The example you link has a non-express version in there as well. It sorta works, in that I can add that code and it doesn't break, however I can't get what's in "var query" out. Is there a toString() I have to call maybe? – Marcel Marino Jun 06 '17 at 20:33
  • @Jonasw The link you posted did lead me to the answer, or part of it. I don't need express apparently, but the answer only gave me an object and not a string. Once I got the var query I had to do query.q to get Person. – Marcel Marino Jun 07 '17 at 13:15

1 Answers1

1

After seeing the link from @jonasw, I was able to get to the correct answer.

If the paramater being sent to the node js file is labeled as q, as in ?q=GetPerson then this is what you need:

var http = require('http'),
fs = require('fs'),
url = require('url');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;
    var q = query.q;    
}).listen(process.env.PORT);

var q will have GetPerson in it.

Marcel Marino
  • 962
  • 3
  • 17
  • 34