0

This being my first attempt at building a server...

I have set up a server to handle a contact form submission that also includes a predefined captcha string.

When the server receives the contact form, if the captcha string is the one expected then I want it to simply respond with a JSON of the parsed contact form query using response.end(JSON.stringify(parsedURL));

If the captcha string is wrong, I want the server to respond "saying" the captcha was wrong, so that the client asks the user to try again. But I don't know how to do that.

ON THE SERVER :

var httpServer = http.createServer(function (request, response)
{
    if (/\/contactform\?....../.test(request.url))
    {
        var parsedURL = url.parse(request.url, true);
        var name  = parsedURL.query.name;
        var email  = parsedURL.query.email;
        var subject  = parsedURL.query.subject;
        var enquiry  = parsedURL.query.enquiry;
        var captcha = parsedURL.query.captcha;

        if (captcha !== "testing")
        {
           // send a "bad" response to the client and include the message "bad captcha"
        }   

        else response.end(JSON.stringify(parsedURL.query));
    }
}).listen(8080);

ON THE CLIENT :

$.ajax({
   url: "/contactform?..............",
   success: function(msg)
   {
      console.log(msg);
   },
   error: function(msg)
   {
      // the "bad captcha" response should be handled here right ?
      console.log(msg); // which should be equivalent to console.log("bad captcha");
   }
});

When I use response.end(JSON.stringify(parsedURL)); the client (jQuery) considers that a "success".

How should I respond from the server so that the "error" part of the ajax request on the client is executed?

Or is the "error" part supposed to handle only cases where the server doesn't respond at all, i.e. when something has gone horribly wrong server-side, like an exception, a real error, and not cases where simply my evaluation on the server doesn't have the expected outcome ?

Should I instead useresponse.end(...); in both cases as in :

ON THE SERVER :

var httpServer = http.createServer(function (request, response)
{
    if (/\/contactform\?....../.test(request.url))
    {
        var parsedURL = url.parse(request.url, true);
        var name  = parsedURL.query.name;
        var email  = parsedURL.query.email;
        var subject  = parsedURL.query.subject;
        var enquiry  = parsedURL.query.enquiry;
        var captcha = parsedURL.query.captcha;
        var response = JSON.stringify(parsedURL.query);

        if (captcha !== "testing") response = "bad captcha";

        response.end(response);
    }
}).listen(8080);

ON THE CLIENT :

$.ajax({
   url: "/contactform?..............",
   success: function(msg)
   {
      console.log(msg); // msg will either be the stringified object or "bad captcha"..
   }
}); 

In other words, when a request is successfully received on the server but the server wants to let the client know that something was missing or whatever, should the response from the server be sent as an "error" (i.e. handled by the "error" block on the client's ajax code) or as a "success" with the appropriate message saying what actually happened?

Kawd
  • 4,122
  • 10
  • 37
  • 68
  • It seems that this question has answers here : http://stackoverflow.com/questions/14154337/how-to-send-a-custom-http-status-message-in-node-express – xShirase Oct 11 '14 at 01:40
  • I saw that but I'm not using express, I'm trying to learn Node.js first and then build my way up.. – Kawd Oct 11 '14 at 01:48

1 Answers1

1

I think what you need to do is set headers of your response.

Here is an example:

var body = 'Sorry!';
response.writeHead(404, {
  'Content-Length': body.length,
  'Content-Type': 'text/plain' });

Refer to http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers for more information.

creeper
  • 499
  • 2
  • 17
  • This code example looks correct, however, I would suggest two slight modifications: First, use a 403 status code instead of 404. Second, keep your original "bad captcha" body content, since it describes the problem to the client. And to answer the larger question, it's typically considered bad practice to return a successful 200 response when in fact there was a problem with the request. – Troy Gizzi Oct 11 '14 at 02:37
  • It's just a simple demo, and you can change it to meet your needs. – creeper Oct 11 '14 at 06:08
  • I ended up sending my response like so :`response.writeHead(403, {"Content-Type": "text/plain"}); response.end("bad captcha");` Is that OK? By the way Troy, the 403 code that you suggested makes an error show on the browser's console (at least on Chrome). Is that OK? How can I avoid that? I believe console errors like this can break IE for example, correct? I think a 403 (forbidden) status seems a bit "harsh"/too much in this scenario doesn't it? – Kawd Oct 11 '14 at 13:31