2014-10-27 48 views
2

我想從NodeJS應用程序發送POST請求到Rails應用程序。http從節點js到嵌套params軌道上的紅寶石

這裏的的NodeJS代碼:

var http = require('http'); 
var photoRequest = { 
    photo_request: { 
     bw_quantity: 0, 
     color_quantity: 1 
    } 
    }; 

var photoRequestStr = JSON.stringify(photoRequest); 
var options = { 
    host: 'localhost', 
    path: '/api/v1/photo_requests', 
    port: '3000', 
    method: 'POST', 
    headers: { 
     'Content-Length': photoRequestStr.length, 
     'Content-Type': 'application/x-www-form-urlencoded' 
    } 
}; 
var str = ''; 

http 
    .request(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function(data) { 
     str += data; 
    }); 

    res.on('end', function() { 
     console.log(str); 
    }) 

    res.on('error', function(error) { 
     console.log(error); 
    }) 
    }) 
    .end(photoRequestStr); 

和這裏的Rails代碼

def safe_params 
    p 'PARAMS:' 
    p params.inspect 
    p 'END PARAMS' 
    params.require(:photo_request).permit! 
end 

def create 
    @request = PhotoRequest.new(safe_params) 

    if @request.save 
     render json: { :message => 'Success!'}, status: :ok, success: true 
    end 
end 

而且我得到這個錯誤:

Started POST "/api/v1/photo_requests" for 127.0.0.1 at 2014-10-27 11:36:00 +0800 
Processing by Api::V1::PhotoRequestsController#create as HTML 
    Parameters: {"{\"photo_request\":{\"bw_quantity\":0,\"color_quantity\":1}}"=>nil} 
    User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = 'xxxxxxxxxxxxxxxxx' ORDER BY "users"."id" ASC LIMIT 1 
    (0.3ms) SELECT COUNT(*) FROM "photo_requests" WHERE "photo_requests"."allocation_status" IN (
'no', 'partial') 
"PARAMS:" 
"{\"{\\\"photo_request\\\":{\\\"bw_quantity\\\":0,\\\"color_quantity\\\":1}}\"=>nil, \"action\"=>\" 
create\", \"controller\"=>\"api/v1/photo_requests\"}" 
"END PARAMS" 
Completed 400 Bad Request in 5ms 

ActionController::ParameterMissing (param not found: photo_request): 

任何想法我如何能得到軌接受來自nodejs的參數?謝謝!

+0

當您在safe_params方法中執行此操作時,會發生什麼'params.require('photo_request')' – ant 2014-10-27 04:07:16

回答

2

將nodeJS標題代碼更改爲'Content-Type': 'application/json'而不是'Content-Type': 'application/x-www-form-urlencoded'使其工作!