我需要在mocha请求之间保持我的会话。
登录后,我在快递会话对象中存储用户ID:
req.session.user = user.id ;
在浏览器上,会话保持不需要任何问题(使用Postman测试)。
但是,我需要让我的REST API可以访问外部应用程序,我不想对我的API上的每个请求进行身份验证。
有没有办法让我能够在mocha中或通过API的客户端应用程序保持两个请求之间的会话?
先谢谢。
英语不是我母亲的语言,我可能没有像我想要的那样清楚。所以我可以提供您可能需要的任何信息来帮助我。
更新
感谢Alberto,我想出了如何使用Supertest让我的会话在Mocha中保持活力。 代理会保留其会话,直到其被销毁或请求注销。 需要做什么是使用相同的代理登录和请求API。
我做的是:
var request = require('supertest'),
should = require('chai').should();
describe('ImageController', function() {
var agent = request.agent('http://localhost:1337') ;
before(function(done){
agent
.post('/auth/local')
.send({identifier: 'email', password: 'password'})
.end(function(err, res) {
if (err) return done(err);
done();
});
})
after(function(done){
agent
.get('/logout')
.end(function(err, res) {
if (err) return done(err);
done();
});
})
describe('POST /image', function(){
it('should return 201 for image creation after login', function (done) {
agent
.post('/image')
.send({name: 'test.png'})
.end(function (err, res) {
if (err) return done(err);
res.status.should.be.equal(201);
done();
});
});
});
});
答案 0 :(得分:3)
使用超级代理功能如何存储cookie。
在supertest docs中有一个例子:https://github.com/tj/supertest#example
带有超级测试示例的Sails.js示例:https://github.com/albertosouza/sails-test-example
测试文件示例snipplet:
var request = require('supertest');
var assert = require('assert');
var authenticated;
describe('Example test', function() {
// use efore all to create custom stub data
before(function(done) {
// use supertest.agent for store cookies ...
// logged in agent
// after authenticated requests
//login and save one agent with your session cookies. Ex:
authenticated = request.agent(sails.hooks.http.app);
authenticated.post('/auth/login')
.send({
email: user.email,
password: user.password
})
.end(function(err) {
done(err);
});
});
describe('authenticated requests', function(){
it ('should access one protected route', function(done){
// use the authenticated agent to do authenticated requests
authenticated.get('/protected')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
console.log('response:', res.text);
done();
});
});
});
});