【问题标题】:How to handle cookies using request method Node.JS如何使用请求方法 Node.JS 处理 cookie
【发布时间】:2017-11-20 04:30:12
【问题描述】:

我是 Node.Js 的新手,我写了两个方法 post 和 get。首先,我希望帖子看起来像 get 请求(异步函数),所以我可以从不同的 js 文件中导出它,但我不确定它现在是否是异步的。其次,我希望 get 请求也能够发送带有 url 的 cookie。

这里是场景: 1-发送发布请求并设置cookie。服务器将引导我到另一个位置。 2- 获取位置并发送获取请求并包含 cookie。

这是我的 POST 代码:

request.post({
headers: { 'content-type': 'application/x-www-form-urlencoded' },
url: 'http://example/login',
body: 'mes=heydude',
followRedirect: true,
form: {
  username: 'usr',
  password: 'pass'
}

}, function (error, response, body) {
if (error) {
  console.log(error)
}
var  setCookie = response.headers['set-cookie']
console.log('login success')
console.log(body)
})

这个方法很好用,但是如何让它成为一个异步函数呢?像下面的获取请求?还有如何让get请求返回cookie和html?

function fetch (url, callback) {
return new Promise(function (resolve, reject) {
request(url, function (error, response, html) {
  if (error) {
    return reject(error)
  }
  if (response.statusCode !== 200) {
    return reject(new Error('error code'))
  }
  return resolve(html)
  })
  })
}

如果有可以在 NPM 上执行此操作的模块,请告诉我,谢谢。 帮助新手并获得奖杯!

【问题讨论】:

    标签: javascript node.js asynchronous cookies


    【解决方案1】:

    如果您使用 Express,则应查看 cookie-parser。这是一个处理 cookie 的库(顾名思义),因此您不必重新发明轮子。

    如果你不知道Express是什么,建议你看看。

    Express 是一个最小且灵活的 Node.js Web 应用程序框架 为 Web 和移动设备提供了一组强大的功能 应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2020-06-04
      • 1970-01-01
      • 2020-08-04
      • 2014-03-11
      • 1970-01-01
      • 2013-03-03
      相关资源
      最近更新 更多