node.js - grunt-contrib-connect - undefined 不是 connect.static 的函数

标签 node.js grunt-contrib-connect

我正在尝试以这样的方式配置 grunt connect

  1. 对于静态页面,它提供 src 目录中的页面
  2. Web 服务调用被中间件拦截并提供静态 json。

虽然 Web 服务调用被正确模拟,但 connect.static 调用最终会给出错误

TypeError: undefined is not a function

虽然我意识到该模块的更高版本中提供了 connect.static,但我已经升级到比该模块更高的版本

这是我的 package.json 文件

{
  "name": "my-angular-seed-project",
  "version": "1.0.0",
  "description": "angular seed with only bower and grunt",
  "main": "index.js",
  "dependencies": {
  },
  "devDependencies": {
    "bower": "^1.4.1",
    "grunt": "^0.4.5",
    "grunt-cli": "^0.1.13",
    "grunt-contrib-connect": ">=0.10.0",
    "grunt-contrib-jshint": "latest",
    "grunt-contrib-uglify": "latest",
    "grunt-contrib-watch": "latest",
    "jshint-stylish": "^2.0.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

这是 gruntfile.js

// Gruntfile.js

// our wrapper function (required by grunt and its plugins)
// all configuration goes inside this function
module.exports = function(grunt) {

    var restEndPoints = {
        "/restapi/users": {"GET":"json-files/users.get.json"},
        "/restapi/users/login": {"GET":"json-files/users.get.json"},
        "/restapi/users/john@gmail.com": {"GET":"json-files/users.get.john.json"},
        "/restapi/nodes": {"GET":"json-files/nodes.get.json","PUT":"json-files/nodes.put.json","POST":"json-files/nodes.put.json"},
        "/restapi/nodes/Node1": {"GET":"json-files/nodes.get.node1.json","DELETE":"json-files/nodes.delete.node1.json"},
        "/restapi/services": {"GET":"json-files/services.get.json","PUT":"json-files/services.put.json","POST":"json-files/services.put.json"},
        "/restapi/services/nginx": {"GET":"json-files/services.get.nginx.json","DELETE":"json-files/services.delete.nginx.json"},
        "/restapi/commands": {"GET":"json-files/commands.get.json","PUT":"json-files/commands.put.json","POST":"json-files/commands.put.json"},
        "/restapi/commands/pwd": {"GET":"json-files/commands.get.pwd.json","DELETE":"json-files/commands.delete.pwd.json"}
    };

    String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;};



  // ===========================================================================
  // CONFIGURE GRUNT ===========================================================
  // ===========================================================================
  grunt.initConfig({

    // get the configuration info from package.json ----------------------------
    // this way we can use things like name and version (pkg.name)
    pkg: grunt.file.readJSON('package.json'),

    // all of our configuration will go here
        watch: {

        },
    // configure jshint to validate js files -----------------------------------
        jshint: {
          options: {
            reporter: require('jshint-stylish') // use jshint-stylish to make our errors look and read good
          },

          // when this task is run, lint the Gruntfile and all js files in src
          build: ['Gruntfile.js', 'src/**/*.js']
        },  

    // configure connect to run server (on test/serve or example)
      connect: {
        server: {
          options: {
            port : 8000,
            hostname : 'localhost',
            base : 'src',
            middleware: function (connect,options){return [
                //Middleware #1 - for rest api calls
              function restapiMiddleware(req, res, next) {
                  if (req.url.indexOf('restapi') > 0){
                    console.log(req.method+' request received for webservice api ['+req.url+']');

                    var match = false;
                    var json_file_to_serve = "";
                    var keys = Object.keys(restEndPoints);
                    keys.forEach(function(urlAsKey) {
                        if (req.url.endsWith(urlAsKey)) {
                            Object.keys(restEndPoints[urlAsKey]).forEach(function(httpMethodsAsKey) {
                                if (req.method == httpMethodsAsKey){
                                        match = true;
                                        json_file_to_serve = restEndPoints[urlAsKey][httpMethodsAsKey];
                                }
                            }); //forEach ends
                        }
                    }); //forEach ends

                    //no match with the url, move along
                    if (match == false) {
                        return next();
                    }
                    if (req.url.endsWith('/login')){
                    res.writeHead(200, { 'user-auth-token':'56f7997504b352cbf6ba6210409e423f5fdac49a','user-enc-email':'lJUXityStsKko/lPr9eJUc5fLFCV5kFm' });
                    }
                    //Finalize this response with json file
                    res.end(grunt.file.read(json_file_to_serve));

                // if not restapi call then goto next middleware
                // can we serve static right here ? 
                }else{
                    return next();
                }
              } // element/middleware one ends so comma just json objects this is awesome
              ,
              //Middleware #2 for static page calls
              function staticMiddleware(connect,options) {
                connect.static(options.base);
                //connect.static('src');
              }
            ] // array ends
            }
          }
        }
      }





  });

  // ===========================================================================
  // LOAD GRUNT PLUGINS ========================================================
  // ===========================================================================
  // we can only load these if they are in our package.json
  // make sure you have run npm install so our app can find these
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');

    //register the task
    grunt.registerTask('serve', ['connect', 'watch']);


};

我在这里错过了一些微不足道的事情吗?

最佳答案

感谢@R4c00n和@Christian Fritz,我正在查看grunt-contrib-connect的gruntfile,它使用serveStatic调用而不是connect.static,是的,模块serve-static是grunt contrib connect的node_modules的一部分。现在,serveStatic(base.options) 也可以连接静态文件。 这是更新后的 grunt 文件部分(但必须首先提供服务静态调用)

    middleware: function (connect,options){return [
      //statically serve pages from src directory
      serveStatic('src'),

      //Middleware #1 - for rest api calls
      function restapiMiddleware(req, res, next) {
                   // middleware code
      }];}

关于node.js - grunt-contrib-connect - undefined 不是 connect.static 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846665/

相关文章:

node.js - 发送交易结果为 "invalid sender"

node.js - nodejs v.0.8.2 cluster TypeError 对象不是函数

ios - 是否可以配置 grunt-contrib-connect 返回的 mime 类型?

node.js - 如何将 Google Compute Engine 配置为对 nodejs 服务器使用 HTTPS?

node.js - 如何测试使用nodemailer发送电子邮件的Sequelize 'afterCreate'钩子(Hook)?

javascript - Node 中的基本回调帮助

javascript - grunt-contrib-connect 和访问被拒绝页面

javascript - Grunt 连接任务和中间件 Access-Control-Allow-Origin

javascript - 为什么 grunt-contrib-connect 的中间件选项的第三个参数未定义?

javascript - Grunt Connect 服务器 CSS 文件为空