LoginSignup
2
3

More than 5 years have passed since last update.

grunt-contrib-connectでhttpヘッダーを設定する

Posted at

middlewareオプションを使って、HTTPヘッダーを設定するmiddlewareを設定すればOK。
yeomanでクロスドメイン通信したくなった時とかに使ってください。

// ヘッダーを設定するmiddlewareを返す関数を定義
var setHeader = function (headers) {
    return function (req, res, next) {
        var key;
        for (key in headers) {
            if (!headers.hasOwnProperty(key)) {
                continue;
            }
            res.setHeader(key, headers[key]);
        }
        next();
    }
}

module.exports = function (grunt) {
    grunt.initConfig({
        // grunt-contrib-configの設定
        connect: {
            options: {

                ...

                // middlewareオプション
                // リクエストにかますmiddlewareを配列で返す
                middleware:  function (connect) {
                    // 設定したいHTTPヘッダーを書く
                    var headers = setHeader({
                        'Access-Control-Allow-Origin': '*',
                        'Access-Control-Allow-Headers': '*',
                        'Access-Control-Allow-Methods': 'GET, POST'
                    });

                    return [headers];
                },

                ...
            },

            

        }
    })
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3