【问题标题】:passing cookie data on MeteorJS HTTP request在 MeteorJS HTTP 请求上传递 cookie 数据
【发布时间】:2014-12-05 15:26:08
【问题描述】:

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

/* 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}

【问题讨论】:

    标签: meteor http-headers httpcookie


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 2018-08-02
      相关资源
      最近更新 更多