http从节点js到嵌套params轨道上的ruby
我试图从一个NodeJS应用程序发送一个POST请求到一个Rails应用程序。
这里是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 params? 谢谢!
将nodeJS头代码改为'Content-Type': 'application/json'
而不是'Content-Type': 'application/x-www-form-urlencoded'
使它成功了!