fetch a file with a post request from host behind proxy in typescript

index.ts
async function postData(url: string, data: any) {
  try {
    const proxyUrl = 'http://your-proxy-url.com'; // Replace with your proxy url
    const response = await fetch(proxyUrl + url, {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    const responseData = await response.json();
    console.log(responseData);
  } catch (error) {
    console.error(error);
  }
}
478 chars
18 lines

In the above code snippet, we are making a POST request to url via a proxy. data is the data to be sent in the request body. We have set the mode to no-cors to indicate that we do not need CORS headers in the response.

We use fetch() to make the request and pass the url and request options object as arguments. The headers object contains the Content-Type header for JSON data. The body contains the request data converted to string format.

We then handle the response using response.json(), which converts the response to a JSON object. We log the response data to the console. If an error occurs during the request, we log the error to the console instead.

Note that you will need to replace proxyUrl with the URL of your proxy server.

gistlibby LogSnag