在MeteorJS HTTP请求上传递cookie数据

时间:2014-12-05 15:26:09

标签: meteor http-headers httpcookie

我已经花了几个小时在网址MeteorJS上实现cookie。我需要做的是,传递一个像'CURLOPT_COOKIE'PHP那样的cookie数据。我无法在他们的文档甚至论坛上找到任何示例代码。现在我有这些功能:

/* HTTP REQUEST */
Meteor.methods({
   httpRequest: function(type, uri, params){
    this.unblock();
    check(type, String);
    check(uri, String);
    check(params, Object);
    try {
        var result = HTTP.call(type, uri, {params: params});
        return result;
    } catch (e) {
        // Got a network error, time-out or HTTP error in the 400 or 500 range.
        return e;
    }
   }
});
// HTTP request with cooki
 getUserDetails: function(session_id, uid){
  var params = {
     headers: {
      Cookie: {
        sessid: session_i
      }
    },      
    uid: uid
  };
  var response =  Meteor.call('httpRequest', "POST", "http://example.com/rest/wp /alt_wp_resources/loaduser.json", params);
  //res = JSON.parse(response.content);  
  return response;
}
// call here
Meteor.startup(function () {
// delay for 5 sec
Meteor.setTimeout(function (){
    Meteor.call('getUserCredentials', 'api12345', '123qweasd', function (error, result) {                   
    // check user authentication
    var success = result.success;
    console.log(result);
    // user has account from lpgp site, let's save him to meteor.
    if (success){
        console.log('success');
        var session_id = result.session_id;
        //console.log(_session_id);
        Meteor.call('getUserDetails', 'SESSba071091c09f79fefd66e4884dcdde50', 68558, function (error, result) {
            if (!error)
                console.log(result);
            else
                console.log(error);         
        });         
    }else
        // app can't find user account from lpgp site.
        console.log(error);             
});
}, 5000);
});

电话会议成功,但刚刚收到成功:false。

响应:

Object {statusCode: 200, content: "{"success":false}", headers: Object, data: Object}

1 个答案:

答案 0 :(得分:3)

服务器端的Meteor的HTTP模块只是npm module named request的包装器。 request npm模块包括支持指定自己的cookie以及将它们保存到cookie jar中(只需点击链接并搜索“cookie”)。默认的cookie jar是tough-cookie,有趣的是,Meteor包含它,即使我没有看到任何方法从Meteor.HTTP使用它。

这些实现细节的结果是您可以直接使用request。我采用类似的方法将请求包装为Meteor的HTTP模块,但不是HTTP提供的受限制的子选项,我的包装器允许完全访问requesttough-cookie的所有功能。很酷的部分是你甚至不需要直接添加request作为依赖,因为它已经是Meteor的依赖。当然,风险是Meteor的更高版本可以使用除request之外的其他内容,并且您的代码会中断。

无论如何,这是我自己的request包装器。它包含一个JSessionID cookie支持的示例,用于进行Jenkins API调用。只需将其放入syncRequest.coffee文件夹下的\server文件中,并确保已添加coffeescript包(Meteor add coffeescript)...或编译我的代码并将其保存到\server文件夹中的.js文件。

request = Npm.require('request')

populateData = (response) ->
  contentType = (response.headers["content-type"] or ";").split(";")[0]
  if _.include([ "application/json", "text/javascript" ], contentType)
    try
      response.data = JSON.parse(response.content)
    catch err
      response.data = null
  else
    response.data = null

normalizeOptions = (uri, options, callback) ->
  unless uri?
    throw new Error("undefined is not a valid uri or options object.")

  if (typeof options is "function") and not callback
    callback = options

  if options and typeof options is "object"
    options.uri = uri
  else if typeof uri is "string"
    options = uri: uri
  else
    options = uri

  return {options, callback}

normalizeResponse = (error, res, body) ->
  response = null
  unless error
    response = {}
    response.statusCode = res.statusCode
    response.content = body
    response.headers = res.headers
    populateData(response)
    if response.statusCode >= 400
      error = makeErrorByStatus(response.statusCode, response.content)
  return {error, response}

wrappedRequest = (uri, options, callback) ->
  {options, callback} = normalizeOptions(uri, options, callback)
  request(options, (error, res, body) ->
    {error, response} = normalizeResponse(error, res, body)
    callback(error, response)
  )

wrappedCall = (method, uri, options, callback) ->
  options.method = method
  wrappedRequest(uri, options, callback)

wrappedGet = (uri, options, callback) -> wrappedCall("GET", uri, options, callback)
wrappedPost = (uri, options, callback) -> wrappedCall("POST", uri, options, callback)
wrappedPut = (uri, options, callback) -> wrappedCall("PUT", uri, options, callback)
wrappedDelete = (uri, options, callback) -> wrappedCall("DELETE", uri, options, callback)

getWithJSession = (j_username, j_password, securityCheckUri, uri, callback) ->
  request = request.defaults({jar: true})

  form = {j_username, j_password}

  request.post({uri: securityCheckUri, form: form}, (error, response, body) ->
    if error?
      throw new Error(error)
    else if response.statusCode isnt 302
      throw new Error("Expected response code 302 (forward). Got #{response.statusCode}")
    else
      request.get(uri, (error, res, body) ->
        {error, response} = normalizeResponse(error, res, body)
        callback(error, response)
      )
  )

syncRequest = Meteor.wrapAsync(wrappedRequest)
syncRequest.call = Meteor.wrapAsync(wrappedCall)
syncRequest.get = Meteor.wrapAsync(wrappedGet)
syncRequest.post = Meteor.wrapAsync(wrappedPost)
syncRequest.put = Meteor.wrapAsync(wrappedPut)
syncRequest.delete = Meteor.wrapAsync(wrappedDelete)
syncRequest.del = syncRequest.delete

syncRequest.getWithJSession = Meteor.wrapAsync(getWithJSession)
syncRequest.getWithJsession = syncRequest.getWithJSession

(exports ? this).syncRequest = syncRequest