node.js - 如何在 Node.js 应用程序上使用相互 SSL 和测试框架 Mocha/Chai(chai-http)
问题描述
我正在开发一个使用相互 SSL 身份验证的应用程序,我想编写自动化测试来评估功能。
我已经实现了服务器,我可以用 Postman 进行测试。这个职位运作良好。
在我的摩卡测试中,我写了这个请求:
chai.request(getServer())
.post('/users')
.ca(fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'))
.cert(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'))
.key(path.join(process.cwd(), 'test', 'client1-crt'), 'utf-8'))
.send(userToCreate)
.end((error, response) => {
if (error !== null) {
reject(`User creation error : ${JSON.stringify(error)}`);
} else if (response.status !== 201) {
reject(`User creation failed : ${JSON.stringify(response.status)}`);
} else {
resolve(response.body);
}
});
但是此请求不会向服务器发送任何证书:
- request.socket.authorized = 未定义
我尝试使用 HTTPS 代理:
let agent = new Agent({
ca: fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'),
key: fs.readFileSync(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'),
cert: fs.readFileSync(path.join(process.cwd(), 'test', 'client1-crt.pem'), 'utf-8')
});
chai.request(getServer())
.post('/users')
.agent(agent)
.send(userToCreate)
.end((error, response) => {
if (error !== null) {
reject(`User creation error : ${JSON.stringify(error)}`);
} else if (response.status !== 201) {
reject(`User creation failed : ${JSON.stringify(response.status)}`);
} else {
resolve(response.body);
}
});
但是此请求不会向服务器发送任何证书:
- request.socket.authorized = 未定义
- 我在 mocha 测试中遇到 ERR_INVALID_PROTOCOL 异常
有人可以帮我吗?
解决方案
我终于通过直接使用superagent而不是chai-http解决了这个问题。尽管 chai-http 使用了 superagent,但看起来实现缺少方法 ca、cert 和 key。所以下面的语法为我解决了这个问题:
superAgent
.post('http:/localhost/users')
.ca(fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'))
.cert(fs.readFileSync(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'))
.key(fs.readFileSync(path.join(process.cwd(), 'test', 'client1-crt'), 'utf-8'))
.send(sentBody)
.end((error, response) => {
if (error !== null) {
reject(`User creation error : ${JSON.stringify(error)});
} else if (response.status !== 201) {
reject(`User creation failed : ${JSON.stringify(response.status)});
} else {
resolve(response.body);
}
}
});
推荐阅读
- python - 如何在 matplotlib 和 ploty 中将 LaTeX 数学表达式与其他字体一起使用?
- javascript - 从事件侦听器更改时 RGB 颜色不更新
- yaml - dhall-to-yaml:表示嵌套在结构化 yaml 中的非结构化块
- parse-platform - 解析查询覆盖旧查询的新查询?
- android - bundle.getString 返回一个空字符串
- python - 我无权使用 Facebook SDK 删除对象
- java - 错误 - 对象引用了未保存的瞬态实例
- c# - 上电掉落位置问题
- excel - 使用 vba 创建 word-document label.list 并填充它
- javascript - 插入元素时触发计算属性