bgm*_*gmn 10 ssl-certificate typescript visual-studio-code vscode-extensions axios
我目前正在开发一个发出 HTTPS GET 请求的 Visual Studio Code 扩展,并且我试图忽略无效的证书,例如过期的证书。
这是一个非常简单的打字稿脚本,可以运行:
import * as https from "https";
import axios from "axios";
try {
const test = async () => {
await axios.get(
'https://expired.badssl.com/',
{
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
}
);
};
test();
} catch (e) {
console.log(e);
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,当我编译文件并运行它时,它不会返回任何内容,如果我更改rejectUnauthorized为true,它会记录过期的证书错误。
但是,当我创建一个简单的打字稿扩展(如https://code.visualstudio.com/api/get-started/your-first-extension中所述)并yo code发出类似的 axios 请求时,它会给出证书已过期错误,无论给定的参数rejectUnauthorized
与上面使用yo code模板制作的类似的打字稿代码:
import * as vscode from 'vscode';
import * as https from "https";
import axios from "axios";
export async function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('nameOfExtension.helloWorld', async () => {
try {
await axios.get(
'https://expired.badssl.com/',
{
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
}
);
} catch (e) {
console.log(e);
}
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
Run Code Online (Sandbox Code Playgroud)
(nameOfExtension其中是扩展名package.json)
扩展的工作原理:用户打开命令面板(在 mac 上为 cmd+P)并运行“hello world”命令来运行 axios 请求。如果有效,则不会发生任何事情,否则错误消息将打印到控制台。
我发现可以使扩展忽略证书的一种方法是添加将https.globalAgent.options.rejectUnauthorized = falseglobalAgent 设置为始终为 false 的代码行。
但在全球范围内设置这个并不是我想要做的事情,我希望它rejectUnauthorized适用于单个实例。
我想知道是否有人知道为什么rejectUnauthorized示例中显示的方法在 vscode 上不起作用?
这是我的想法:
附加信息:
"devDependencies": {
"@types/vscode": "^1.61.0",
"@types/glob": "^7.1.4",
"@types/mocha": "^9.0.0",
"@types/node": "14.x",
"@typescript-eslint/eslint-plugin": "^4.31.1",
"@typescript-eslint/parser": "^4.31.1",
"eslint": "^7.32.0",
"glob": "^7.1.7",
"mocha": "^9.1.1",
"typescript": "^4.4.3",
"@vscode/test-electron": "^1.6.2"
},
"dependencies": {
"axios": "^0.21.4",
"https": "^1.0.0"
}
Run Code Online (Sandbox Code Playgroud)
小智 0
您尝试过使用承诺吗?
否则你可以像这样使用它:
const axios = require('axios');
return new Promise((resolve, reject) => {
axios
.get('https://expired.badssl.com/', {
responseType: 'arraybuffer',
responseEncoding: 'binary'
}).catch(e => e + 'Get reqeust failed.')
.then(response => {
const data = response.data
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |