Disregarding axios error due to invalid certificates while developing a visual studio code extension

I'm currently developing a Visual Studio Code extension that involves making HTTPS GET requests. I'm working on ignoring invalid certificates, specifically expired certificates.

Below is a simple TypeScript script that successfully achieves this:

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);
}

Upon compiling and running the script, the expected outcome is that nothing is returned. If the rejectUnauthorized parameter is set to true, an error related to the expired certificate is logged.

However, when a TypeScript extension is created using the https://code.visualstudio.com/api/get-started/your-first-extension guide with the yo code command, a similar axios request results in a certificate expired error, regardless of the parameter value passed to rejectUnauthorized.

Snippet of TypeScript code generated using 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() {}

(where nameOfExtension corresponds to the extension name in package.json)

Functionality of the extension: Users can trigger the 'hello world' command from the command palette (cmd+P on mac) to execute the axios request. If successful, no action is taken, otherwise, an error message is printed to the console.

One workaround I discovered to make the extension ignore the certificate issue is by adding the line of code

https.globalAgent.options.rejectUnauthorized = false
, which forces the globalAgent to always return false.

However, I prefer not to set this globally and would like the rejectUnauthorized to function for individual instances.

I'm curious to know why the rejectUnauthorized method in the example does not work within vscode?

Here are a few thoughts I have on this:

  • Could it be related to the environment?
  • Is the global setting automatically applied when the extension runs, possibly overriding the local setting I'm trying to implement?

Additional information:

"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"
}

Answer №1

Have you given a promise a shot?

If not, you can implement it this way:

const axios = require('axios');

return new Promise((resolve, reject) => {

   axios
       .get('https://expired.badssl.com/', {
             responseType: 'arraybuffer',
             responseEncoding: 'binary'
       }).catch(e => e + 'Request failed.')
       .then(response => {
            const data = response.data
       })
})

Answer №2

Here is how I found a solution:

const webLink = "your_web_link";
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
let successResponse = await axios.get(webLink); //this one should be successful
process.env.NODE_TLS_REJECT_UNAUTHORIZED = undefined;

//After setting it back to undefined, the next request should fail. 
//So, I implemented a temporary solution for a specific request:
let failResponse = await axios.get(webLink); //this one should fail

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting formData for a boolean in an Axios post request: a step-by-step guide

I am having trouble sending a post request using axios to my backend. It seems that I cannot include the boolean value "isActive" in the request. Is there a solution to this issue? async submit() { const isValid = await this.$validator.validateAll() ...

Concealing .js files while working with .ts extensions

After installing TypeScript for Visual Studio 2015, I noticed that when I write a .ts file, it creates a .js file at the same level in my solution. Is there a way to hide the .js file or have it integrated within the .ts file so that I can simply expand ...

Tips for effectively passing generics to React Hooks useReducer

I am currently working with React Hooks useReducer in conjunction with Typescript. I am trying to figure out how to pass a type to the Reducer Function using generics. interface ActionTypes { FETCH, } interface TestPayload<T> { list: T[]; } inter ...

Tips for including a sequelize getter in a model instance?

I'm currently struggling to add a getter to the name field of the Company model object in my project. Despite trying various approaches, I haven't had any success so far. Unfortunately, I also couldn't find a suitable example to guide me thr ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

execute a post request with dynamic data to API using nextjs httpService

I am trying to make a call to an endpoint located at using nestjs. However, I keep encountering the following error message: data 13 - XML tags should be given in the POST variable "data" const { data } = await firstValueFrom( this.httpService .post ...

Error in NextJS with TypeScript when updating data in a useState variable

Recently, I started working with TypeScript, ReactJS, and NextJS, but I encountered a TypeScript error that I need help fixing. My current project involves using NextJS 14, server actions, and Prisma as the ORM for a university-related project. An issue ar ...

Is it possible to utilize an angular 1 template in conjunction with angular 2?

I am currently working on developing a real-time reactive admin dashboard for a Dashboard/POS system. While I primarily work with Java and have experience with .net, I have recently started practicing with the MEAN stack for creating real-time web applicat ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

Guide to adding information to a table with the help of an "interface" in Angular 6 and utilizing Typescript

Looking for some guidance with Angular as I am just starting out. I am currently trying to send an API request in angular 6 using Typescript. However, I am facing difficulties when it comes to adding data to a table. Check out my code on: Codepen In my p ...

Can you demonstrate how to display the chosen toggle button within Angular 4 alongside the remaining options?

I have created a custom toggle button component in Angular that I can reuse in different parts of my application. However, I am facing an issue that I need help resolving. I want to display only the selected toggle button and hide the others. When I click ...

Learn how to dynamically adjust context using a server-client architecture with TRPC

Currently, I am referring to the tRPC documentation for guidance on creating a server side caller. But I'm facing a challenge in dynamically setting the value when incorporating it into my NextJS 13 pages. In my context.ts file, you will find the fol ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

Conflicting configurations in VS Code causing issues

Currently making adjustments to my JSON settings and everything is functioning correctly, however, I keep encountering this persistent error: "Expected comma jsonc(514)" Here's a snippet of my code that's causing the issue: "css.li ...

A more efficient method for defining and utilizing string enums in Typescript

enum PAGES { HOME = 'HOME', CONTACT = 'CONTACT', } export const links: { [key: string]: string } = { [PAGES.HOME]: '/home', [PAGES.CONTACT]: '/contact', }; export function getLink(page: string) { return B ...

What is the functionality of input onChange in React when using state management?

Whenever I try to log the value of the input after each onChange event, there seems to be an odd one event delay. For example, if 'some text' is the default input value and I remove the letter 't' by pressing backspace/delete, it first ...

A guide on how to navigate to a customizable element in React Native

After creating a glossary, I needed a way to access the content of a specific letter by clicking on that letter from a list displayed at the top of my page. However, I encountered an issue - while I managed to implement scrolling functionality, I couldn&ap ...

How to transfer the label text value from html to .ts file in Ionic 3?

Hey everyone! I just started using Ionic and I'm wondering how to pass the value of a label text from HTML to the .ts file. Here's a snippet of my code: <div class="box" (click)="openChatBot()"></div> <ion-label>LEADER ...

What is the best method for resetting the user state to null?

I'm currently utilizing VueX in Nuxt with Typescript. My goal is to set the initial state of my user to null. When I try setting state.authenticatedUser:null, everything works smoothly. However, when I attempt to assign an IAuthenticatedUser type to i ...