节点请求如何处理会话

我使用node.JS和请求模块。

我的问题是,我需要对每个请求进行身份validation,因为会话在.then((response) => {})块之外被销毁。

如何将创build的会话保存在一个类中供以后使用?

我尝试了一切都没有成功。

这是一个不工作的代码片段

 login() { const getLoginUrl = 'https://www.demourl.com/' const postLoginUrl = 'https://www.demourl.com/account/login/' rp({ url: getLoginUrl, jar: this.cookieJar, method: 'GET' }) .then((body) => { var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0]; var args = { url: postLoginUrl, json: true, method: 'POST', data: { username: this.username, password: this.password }, headers: { 'method': 'POST', 'path': '/account/login/', 'cookie': 'csrftoken=' + csrftoken, }, jar: this.cookieJar, resolveWithFullResponse: true } rp(args) .then((response) => { //Here is a valid session //But how can I use this session in different functions? console.log('Post demourl.com/account/login success'); }) .catch((error) => { console.log('Post demourl.com/account/login error: ', error); }); }) .catch((error) => { console.log('Get demourl.com error: ', error); }); } 

你应该使用这个函数作为中间件,然后附加你想要附加到你的需求

尝试在你的主要脚本做

 'use strict' const express = require('express'); const login = require('./login'); const app = express() app.use(login);// use this if you want all your routes to check login or put it in a specific route app.get('/', (req,res)=>{ //this route is only for loged in users }); const server = http.createServer(app).listen(process.env.PORT); module.exports = app; 

我从来没有看到this.cookieJar被定义。 确保它在某处被初始化:

 this.cookieJar = request.jar(); 

如果您只在应用程序中使用单个CookieJar,则还可以通过将选项jar设置为true来使用Request的全局Cookie jar:

 // Either by setting it as the default const request = require('request').defaults({jar: true}); // Or by setting it on each request request('www.example.com', { jar: true });