1

I am trying to do something seemingly very simple but I'm having trouble working it out. Users can submit some text using a HTML form with POST method. This is then sent off to an API for processing, and returns with a JSON object. I then just want the app.js file to send this JSON object back so I can play around with it using JQuery. Here is the .post method in my app.js

app.post('/', function(req, res){
 console.log("starting app.post");

  // See User Modeling API docs. Path to profile analysis is /api/v2/profile
  // remove the last / from service_url if exist
  var parts = url.parse(service_url.replace(/\/$/,''));

  var profile_options = { host: parts.hostname,
    port: parts.port,
    path: parts.pathname + "/api/v2/profile",
    method: 'POST',
    headers: {
      'Content-Type'  :'application/json',
      'Authorization' :  auth }
    };

  // create a profile request with the text and the https options and call it
      create_profile_request(profile_options,req.body.content)(function(error,profile_string) {
        if (error) {res.render('home.html',{'error': error.message});
                        console.log("errormessage: "+error.message);
      }
    else {
      // parse the profile and format it
      var profile_json = JSON.parse(profile_string);
      var flat_traits = flatten.flat(profile_json.tree);      
      // Extend the profile options and change the request path to get the visualization
      var fileName="file 1"; //this will eventually be imported automatically
      //console.log(flat_traits);     
      var scoreObject={"title":fileName, "percentage":functions.matchPercentage(flat_traits)}
  res.send(scoreObject); //this is what I assume should send this back client-side      
          });
    }
  });
    });

// creates a request function using the https options and the text in content
// the function that return receives a callback
var create_profile_request = function(options,content) {
  return function (/*function*/ callback) {
    // create the post data to send to the User Modeling service
    var post_data = {
  'contentItems' : [{ 
    'userid' : 'dummy',
    'id' : 'dummyUuid',
    'sourceid' : 'freetext',
    'contenttype' : 'text/plain',
    'language' : 'en',
    'content': content
  }]
    };
// Create a request to POST to the User Modeling service
var profile_req = https.request(options, function(result) {
  result.setEncoding('utf-8');
  var response_string = '';

  result.on('data', function(chunk) {
    response_string += chunk;
  });

  result.on('end', function() {

    if (result.statusCode != 200) {
      var error = JSON.parse(response_string);
      console.log("status: "+result.statusCode);
      callback({'message': error.user_message}, null);
      console.log(error.user_message);
    } else
      callback(null,response_string);
  });
});

profile_req.on('error', function(e) {
  callback(e,null);
});

profile_req.write(JSON.stringify(post_data));
profile_req.end();
  }
 };

So I presume res.send is what passes the data across to the client-side, but then how do I receive the data on the client-side? This is my attempt at the JScript:

$.getJSON('/').done(function(data){
$('#resultsList').append('<li data-icon="arrow-r" data-iconpos="right" id="'+
        data.title+'">  <a href="#breakdownDialog"> <div id="cvResults"><h3>'+
        data.title+'</h3>   <span>'+data.percentage+
        '%</span></div></a><div id="output"></div></li>');
console.log(data.title+data.percentage);
}
});

I want to take some of the values from the JSON object and put them in a list on the existing HTML page. At the moment this just takes me to a different blank page that says Undefined. How should I grab the JSON data from the server?

EDIT: Here's the HTML form I am submitting the data with:

<form method="POST" id="submitForm">
                <fieldset>
                    <textarea id="textArea" required="true" rows="5" name="content"></textarea>
                    <button class="btn btn-block" type="submit">
                            Analyse         
                    </button>
                </fieldset>
                </form>
3
  • If you return json, why not use res.json Commented Mar 2, 2015 at 22:37
  • Do you target="_blank" attribute set on your form element? It would be useful to have the html in the question as weel Commented Mar 3, 2015 at 9:06
  • I've now added the HTML in Commented Mar 3, 2015 at 9:23

1 Answer 1

1

Are you sure that you are sending json with res.send()? Try to set header res.set('Content-Type', 'application/json') or use this res.json() instead of res.send()

Sign up to request clarification or add additional context in comments.

4 Comments

That's a good point. I tried this though and I still have the same problem at the client side, can't seem to get it to work as expected. Am I doing something wrong with my JQuery code?
I guess that the problem is in submitting the form using plain HTML. In my opinion, it will be better to use AJAX. Using this code - jsfiddle.net/1bvxr56v you will receive your data without reloading the page, so maybe it is necessary to change success method.
It makes sense to me that you would set up the method for posting there...submitting it purely through HTML didn't make much sense to me. Now I don't understand how the server-side code changes. There's a load of account information (like the URL, username etc) that should be client-side. Can I pass the client-side data into the server-side somehow?
You passing your client-side data using AJAX. You get this data from inputs etc using jQuery methods like val(). On server it will be accessible in req.body object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.