0

我正在为我的项目开发一个紧凑的 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命令调用 url 或通过 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

非常感谢您的宝贵时间。

4

1 回答 1

0

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

过滤 /favicon.ico 的请求,使其被忽略,或者为此资源提供某种响应。

于 2013-10-01T14:54:39.303 回答