简体   繁体   中英

How to handle cookies using request method Node.JS

I'm new to Node.Js, and I have written two methods post and get. First of all I want the post to look like the get request (asynchronous function) so I can export it from a different js file, but I'm not sure if it is asynchronous right now. Second, I want the get request to be able to send a cookie with the url also.

here is the scenario: 1- send a post request and set the cookie. The server will direct me to another location. 2- get the location and send a get request and include the cookie.

here is my code for 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)
})

This method works fine but how to make it an asynchronous function? like the below get request? also how to make the get request returns the cookie and the 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)
  })
  })
}

If there is ane module that can do that on NPM let me know thanks. Help a newbie and get a trophy!

If you are using Express, you should look at cookie-parser . This is a library that handles cookies (as the name suggests) so you don't have to reinvent the wheel.

If you don't know what Express is, I suggest you to look at it.

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

The requests library is asynchronous, so your existing code should be fine. In regards to setting a cookie, use res.cookie : http://expressjs.com/en/api.html#res.cookie

Edit: if you want to use Promises as in the get request, take a look here: https://github.com/request/request#promises--asyncawait

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM