我是Node.js的新手。我正在尝试创建一个web服务器,1)提供静态的html网页,2)提供一个基本的JSON / REST。我的管理层告诉我,我必须使用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?
谢谢
发布于 2013-10-19 08:26:09
从未使用过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));
}发布于 2017-05-19 17:32:41
2017年,现代的做法是:
server.get('/rest/customer', (req,res) => {
let customer = {
data: 'sample value'
};
res.json(customer);
});https://stackoverflow.com/questions/19459369
复制相似问题