Mac OS X NodeJS: has no method 'router' error

霸气de小男生 提交于 2019-12-01 11:19:13

Alright, it's hard to say since it really looks like the tutorial you are following isn't using connect, but here is an example using connect that should work.

function sendJSON(response, obj) {
  response.writeHead(200, {'Content-Type':'application/json'});
  var objStr = JSON.stringify(obj);
  response.end(objStr);
}

function get(path, cb) {
  return function(req, res, next) {
    if (req.method != 'GET' || req.url != path) return next();
    cb(req, res, next);
  }
}

var connect = require('connect')
var app = connect()
  .use(connect.query())
  .use(get('/foo', function(req, res, next) {
    sendJSON(res, {path: 'foo'});
  }))
  .use(get('/bar', function(req, res, next) {
    sendJSON(res, {parth: 'bar'});
  }))
  .listen(3000);

Install express and slightly rewrite the code:

var express = require('express');
var util    = require('util');

function sendjson(res,obj)
{
    res.writeHead(200, {
        'Content-Type': 'application/json',
    });

    var objstr = JSON.stringify(obj);
    util.debug('SENDJSON:' + objstr);
    res.end(objstr);
}


var app = express();

app.get('/foo', function(req,res) {
    sendjson(res, {path:'/foo'});
});

app.get('/bar', function(req,res) {
    sendjson(res, {path:'/bar'});
});

app.listen(3000);
util.debug('Server running at http://127.0.0.1:3000');

I had the same question. Richard Rodger,the author of 'Beginning Mobile Application Development in the Cloud' suggested I should either use the dispatch module (https://github.com/caolan/dispatch) or install an older version of connect, using:

npm install git://github.com/senchalabs/connect.git#1.8.6

Hope this helps! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!