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

Can't access via browser when using restify?

本文关键字:浏览器 访问 restify 使用      更新时间:2023-09-26

我正在为我的项目开发一个紧凑的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

非常感谢您的时间。

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

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