Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

static response via request.send #42

Closed
captn3m0 opened this issue Sep 9, 2011 · 2 comments
Closed

static response via request.send #42

captn3m0 opened this issue Sep 9, 2011 · 2 comments

Comments

@captn3m0
Copy link

captn3m0 commented Sep 9, 2011

I wanted to write a complete application using restify, which would be mostly a webservice, but with a few (2-3) client. The issue is that I am unable to server simple static resources using restify as it automatically json-encodes them.

If file test.html contains 1234

Then

server.get('/',function(req,res){
fs.readFile('test.html','utf-8',function(err,data){
    if(err){
        res.send(100,{msg:"There was an error in handling your request"});
        err.next();
    }
    else{
        console.log(data);
        res.send(200,data,{'Content-Type':'text/html; charset=utf-8'});
    }
});
});

gives me "1234\n" as the output on opening localhost:8080/ on the browser.

I was able to make this work by following the example in http://mcavage.github.com/node-restify/restify-response.7.html but I feel that it should be easier to send simple html responses. (Instead of going around res.write)

@mcavage
Copy link
Contributor

mcavage commented Sep 10, 2011

This is actually possible by using a custom contentWriter (here's one I use for text/plain):

server = restify.createServer({
  accept: ['text/plain', 'application/json', 'text/html', 'image/png'],
  contentWriters: {
    'text/plain': function(obj) {
      if (!obj)
        return '';
      if (typeof(obj) === 'string')
        return obj;
      return JSON.stringify(obj, null, 2);
    }
  }
});

And later on res.send(HttpCodes.Ok, 'Hello World');

That will get automatically invoked based on the client's accept header. Does that help?

@captn3m0
Copy link
Author

Thanks, that should do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants