使用restify时无法通过浏览器访问?

时间:2013-09-19 19:02:23

标签: javascript node.js curl restify

我正在为我的项目开发一个紧凑的API,然后我选择nodejs,restify和mongodb。我有这样的代码:

var restify = require('restify');
var mongoose = require('mongoose');

var httpPort = process.env.PORT || 5000;
var uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/mydb';

db = mongoose.connect(uristring);
Schema = mongoose.Schema;

var myServer = restify.createServer({
    formatters: {
        'application/json': function(req, res, body){
            if(req.params.callback){
                var callbackFunctionName = req.params.callback.replace(/[^A-Za-z0-9_\.]/g, '');
                return callbackFunctionName + "(" + JSON.stringify(body) + ");";
            } else {
                return JSON.stringify(body);
            }
        },
        'text/html': function(req, res, body){
            return body;
        }
    }
});

senseServer.use(restify.bodyParser());

var getHome = function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); 
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.contentType = 'json';
  res.send({version: '0.1', email: 'setfiretotherain@yahoo.com'});
}

myServer.listen(httpPort, function() {      
  var consoleMessage = '\n\n myServer is listening at %s \n\n';    
  console.log(consoleMessage, senseServer.url);
});

myServer.get('/', getHome);

如果我使用 curl 命令来调用网址或通过http:// [localhost]:5000进行访问,它可以正常工作。

curl -X GET http://[localhost]:5000
curl -X GET http://domain.com:5000

但是,当我尝试通过浏览器进行访问时,例如http://domain.com,它会显示一次json内容,然后应用程序崩溃,并出现如下错误(我在日志文件中):

http.js:854
    throw new TypeError('first argument must be a string or Buffer');
          ^
TypeError: first argument must be a string or Buffer
    at ServerResponse.OutgoingMessage.write (http.js:854:11)
    at _cb (/root/server/node_modules/restify/lib/response.js:188:30)
    at ServerResponse.send (/root/server/node_modules/restify/lib/response.js:199:25)
    at emitRouteError (/root/server/node_modules/restify/lib/server.js:151:21)
    at onRoute (/root/server/node_modules/restify/lib/server.js:623:33)
    at Router.find (/root/server/node_modules/restify/lib/router.js:467:9)
    at Server._route (/root/server/node_modules/restify/lib/server.js:617:21)
    at routeAndRun (/root/server/node_modules/restify/lib/server.js:576:22)
    at Server._handle (/root/server/node_modules/restify/lib/server.js:596:17)
    at Server.onRequest (/root/server/node_modules/restify/lib/server.js:258:22)
error: Forever detected script exited with code: 8
error: Forever restarting script for 2 time

非常感谢你的时间。

1 个答案:

答案 0 :(得分:0)

您的浏览器可能正在尝试加载图标。

过滤/favicon.ico的请求,以便忽略它或为此资源提供某种响应。