Search code examples
gruntjsgrunt-contrib-connect

How to allow grunt-contrib-connect to allow POST,PUT,DELETE methods on static files?


I have a static project and I am hitting dummy seed JSON files, however its only allowing me to access them via GET. Here is my grunt configuration file, does anyone know how I would allow POST?

module.exports = function(grunt) {
    // Configure
    grunt.config.set('connect', {
        server: {
            options: {
                hostname: '*',
                middleware: function(connect) {
                    return [
                        function(request, response, next) {
                            response.setHeader('Access-Control-Allow-Origin', '*');
                            response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
                            response.setHeader('Access-Control-Allow-Headers', 'Content-Type');

                            return next();
                        },
                        connect.static(require('path').resolve('.'))
                    ];
                }
            }
        }
    });

    // Load Task
    grunt.loadNpmTasks('grunt-contrib-connect');
};

Solution

  • This is my solution, hope can help you, I only check base[0], you can extend it.

    The important is use : middlewares.unshift, not push

    connect: {
      dev: {
        options: {
          // 经过测试 connect插件会依照base的定义顺序检索文件
          // 这意味着如果存在相同文件,定义在前面的会优先返回
          base: ['app', '.'],
          port: 8888,
          // open: true,
          livereload: true,
          hostname: 'localhost',
          middleware: function (connect, options, middlewares) {
            var fs = require('fs');
            var path = require('path');
            var support = ['POST', 'PUT', 'DELETE'];
            middlewares.unshift(function (req, res, next) {
              // 单独处理POST请求 请求的地址必须是文件 这里没有进行rewrite处理
              if (support.indexOf(req.method.toUpperCase()) != -1) {
                var filepath = path.join(options.base[0], req.url);
                if (fs.existsSync(filepath) && fs.statSync(filepath).isFile()) {
                  return res.end(fs.readFileSync(filepath));
                }
              }
    
              return next();
            });
    
            return middlewares;
          },
        }
      }
    }