无法使用RESTIFY从REST API返回JSON

时间:2013-10-18 21:32:18

标签: node.js restify

我是Node.js的新手。我正在尝试创建一个Web服务器,它将1)提供静态html网页,2)提供基本的JSON / REST API。我的管理层告诉我,我必须使用RESTIFY(我不知道为什么)。目前,我有以下内容:

var restify = require('restify');
var fs = require('fs');
var mime = require('mime');
var ecstatic = require('ecstatic');

var ws = restify.createServer({
  name: 'site',
  version: '0.2.0'
});

ws.use(restify.acceptParser(server.acceptable));
ws.use(restify.queryParser());
ws.use(restify.bodyParser());
ws.use(ecstatic({ root: __dirname + '/' }));

ws.get('/rest/customers', findCustomers);

ws.get('/', ecstatic({ root:__dirname }));
ws.get(/^\/([a-zA-0-9_\.~-]+\/(.*)/, ecstatic({ root:__dirname }));

server.listen(90, function() {
  console.log('%s running on %s', server.name, server.url);
});

function findCustomers() {
  var customers = [
    { name: 'Felix Jones', gender:'M' },
    { name: 'Sam Wilson', gender:'M' },
    { name: 'Bridget Fonda', gender:'F'}
  ];
  return customers;
}

启动Web服务器后,我尝试在浏览器中访问http://localhost:90/rest/customers/,然后发出请求。然而,它只是坐在那里,我似乎永远不会得到回应。我正在使用Fiddler监控流量,结果长时间保持为“ - ”。

如何从此类REST调用中返回一些JSON?

谢谢

2 个答案:

答案 0 :(得分:4)

2017年,现代化的方法是:

server.get('/rest/customer', (req,res) => {
  let customer = {
    data: 'sample value'
  };

  res.json(customer);
});

答案 1 :(得分:3)

从未使用ecstatic,但我认为您不需要静态内容的文件服务器,因为您运行restify并返回json。

由于您未以res.send

终止,因此未收到回复

以下代码看起来不错

ws.get('/rest/customers', findCustomers);

但请尝试更改findCustomers这样的功能

function findCustomers(req,res,next) {
  var customers = [
    { name: 'Felix Jones', gender:'M' },
    { name: 'Sam Wilson', gender:'M' },
    { name: 'Bridget Fonda', gender:'F'}
  ];
 res.send(200,JSON.stringify(customers));
}