节点请求如何处理会话
我使用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 });
- 由于连接不再使用parseCookie方法,我们如何使用express来获取会话数据?
- 会话没有定义sailsjs
- 在node.js中,如何使用socket.io设置redis并进行expression? 特别使用RedisStore()
- 如何使用NodeJs的会话variables?
- 会话cookie在Electron中不起作用
- Node / Express应用程序使用connect-flash时无法获取Flash消息
- 节点js +expression+会议
- req.session.passport和req.user空,serializeUser和deserializeUser都不会被调用
- Nodejs + Passport.js + Redis:如何在Redis中存储会话