سؤال

I'm new to Node.js. I'm trying to create a web server that will 1) serve up static html web pages and 2) provide a basic JSON / REST API. I've been told by my management that I must use RESTIFY (I don't know why). Currently, I have the following:

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

After I start the web server, and I try to visit http://localhost:90/rest/customers/ in my browser, the request is made. However, it just sits there and I never seem to get a response. I'm using Fiddler to monitor the traffic and the result stays as '-' for a long time.

How can I return some JSON from this type of REST call?

Thank you

هل كانت مفيدة؟

المحلول 2

never worked with ecstatic but i don't think you need a file server for static content since you run restify and return json.

you are not getting a response because you don't terminate with res.send

the following code looks ok

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

but try to change the findCustomers function like this

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));
}

نصائح أخرى

At 2017, the modern way to do this is:

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

  res.json(customer);
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top