返回列表

restify 输出 HTML

默认分类 2013/09/28 20:00

restify默认输出JSON,直接使用res.send('<button>')会变成\<\button\\>, 因此需要使用res.write()的方式来输出HTML。

var restify = require('restify');

global.api = restify.createServer({
    name: 'myapp',
    version: '1.0.0'
});

api.use(restify.acceptParser(api.acceptable));
api.use(restify.queryParser());
api.use(restify.bodyParser());

// Static resource
api.get(/^\/((.*)(\.)(.+))*$/, restify.serveStatic({ directory: 'public', 
        default: 'index.html' }));


// For test
api.get(conf.api.subdir + '/echo/:name', function (req, res, next) {
    res.send(req.params);
    return next();
});
api.get(conf.api.subdir + '/test/:name', function (req, res, next) {
    var body = '<html><body>hello</body></html>';
    res.writeHead(200, {
        //'Content-Length': Buffer.byteLength(body),
        'Content-Type': 'text/html'
    });
    res.write(body);
    res.end();
    return next();
});

// Start server
api.listen(8080, function () {
    console.log('%s listening at %s', api.name, api.url);
});