【问题标题】:Unable to return JSON from REST API with RESTIFY无法使用 RESTIFY 从 REST API 返回 JSON
【发布时间】:2013-10-27 20:53:10
【问题描述】:

我是 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;
}

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

如何从这种类型的 REST 调用中返回一些 JSON?

谢谢

【问题讨论】:

    标签: node.js restify


    【解决方案1】:

    在 2017 年,实现这一目标的现代方式是:

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

    【讨论】:

      【解决方案2】:

      从未与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));
      }
      

      【讨论】:

      • 或者只是res.send(customers)
      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多