CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tns-core-modules

NativeScript Core Modules compatibility package for building native iOS and Android apps using JavaScript and CSS

Pending
Overview
Eval results
Files

http-client.mddocs/

HTTP Client

Full-featured HTTP client for REST API calls, file downloads, and network communication. The HTTP module provides both high-level convenience methods and low-level request configuration for comprehensive network operations.

Capabilities

HTTP Namespace

Core HTTP functionality providing convenience methods for common network operations.

/**
 * HTTP client namespace with convenience methods
 */
namespace Http {
  // Convenience methods
  function request(options: HttpRequestOptions): Promise<HttpResponse>;
  function getJSON<T>(url: string): Promise<T>;
  function getString(url: string): Promise<string>;
  function getFile(url: string, destinationFilePath?: string): Promise<File>;
  function getImage(url: string): Promise<ImageSource>;
}

Usage Examples:

import { Http } from "tns-core-modules";

// GET JSON data
async function fetchUserData(userId: string) {
  try {
    const user = await Http.getJSON<User>(`https://api.example.com/users/${userId}`);
    console.log("User:", user);
    return user;
  } catch (error) {
    console.error("Failed to fetch user:", error);
  }
}

// GET string content
async function fetchTextContent(url: string) {
  const content = await Http.getString(url);
  return content;
}

// Download file
async function downloadFile(url: string, localPath: string) {
  const file = await Http.getFile(url, localPath);
  console.log("Downloaded to:", file.path);
  return file;
}

// Download image
async function loadImage(imageUrl: string) {
  const imageSource = await Http.getImage(imageUrl);
  return imageSource;
}

HTTP Request Configuration

Comprehensive request configuration interface for advanced HTTP operations.

/**
 * HTTP request options interface
 */
interface HttpRequestOptions {
  url: string;
  method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
  headers?: { [key: string]: string };
  content?: string | HttpContent | any;
  timeout?: number;
  dontFollowRedirects?: boolean;
  
  // Authentication
  username?: string;
  password?: string;
  
  // SSL/TLS
  allowLargeResponse?: boolean;
}

/**
 * HTTP content interface for request bodies
 */
interface HttpContent {
  data: any;
  contentType: string;
}

Advanced Request Examples:

import { Http, HttpRequestOptions } from "tns-core-modules";

// POST with JSON data
async function createUser(userData: any) {
  const options: HttpRequestOptions = {
    url: "https://api.example.com/users",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + getAuthToken()
    },
    content: JSON.stringify(userData),
    timeout: 30000
  };
  
  const response = await Http.request(options);
  return response.content.toJSON();
}

// PUT with form data
async function updateProfile(profileData: any) {
  const formData = new FormData();
  Object.keys(profileData).forEach(key => {
    formData.append(key, profileData[key]);
  });
  
  const options: HttpRequestOptions = {
    url: "https://api.example.com/profile",
    method: "PUT",
    content: formData,
    headers: {
      "Authorization": "Bearer " + getAuthToken()
    }
  };
  
  return await Http.request(options);
}

// DELETE with authentication
async function deleteResource(resourceId: string) {
  const options: HttpRequestOptions = {
    url: `https://api.example.com/resources/${resourceId}`,
    method: "DELETE",
    headers: {
      "Authorization": "Bearer " + getAuthToken()
    }
  };
  
  const response = await Http.request(options);
  return response.statusCode === 204;
}

HTTP Response Interface

Response interface providing access to response data, headers, and status information.

/**
 * HTTP response interface
 */
interface HttpResponse {
  statusCode: number;
  content: HttpContent;
  headers: { [key: string]: string };
  
  // Response body access methods  
  textContent: string;
}

/**
 * HTTP response content interface
 */
interface HttpContent {
  raw: any;
  
  // Content conversion methods
  toString(): string;
  toJSON(): any;
  toImage(): Promise<any>;
  toFile(destinationFilePath?: string): Promise<File>;
}

/**
 * HTTP response encoding options
 */
enum HttpResponseEncoding {
  UTF8 = "utf8",
  GBK = "gbk",
  ISO88591 = "iso88591"
}

Response Handling Examples:

import { Http, HttpResponse } from "tns-core-modules";

async function handleApiResponse() {
  const response = await Http.request({
    url: "https://api.example.com/data",
    method: "GET"
  });
  
  // Check status code
  if (response.statusCode === 200) {
    // Access response data
    const jsonData = response.content.toJSON();
    console.log("Data:", jsonData);
    
    // Access headers
    const contentType = response.headers["content-type"];
    const serverTime = response.headers["date"];
    
    return jsonData;
  } else {
    throw new Error(`HTTP ${response.statusCode}: ${response.content.toString()}`);
  }
}

// Handle different content types
async function processResponse(response: HttpResponse) {
  const contentType = response.headers["content-type"] || "";
  
  if (contentType.includes("application/json")) {
    return response.content.toJSON();
  } else if (contentType.includes("text/")) {
    return response.content.toString();
  } else if (contentType.includes("image/")) {
    return await response.content.toImage();
  } else {
    // Handle binary content
    return response.content.raw;
  }
}

Headers Interface

HTTP headers management for request and response header handling.

/**
 * HTTP headers interface
 */
interface Headers {
  [key: string]: string;
}

/**
 * Common HTTP headers constants
 */
namespace HttpHeaders {
  const CONTENT_TYPE: "Content-Type";
  const AUTHORIZATION: "Authorization";
  const ACCEPT: "Accept";
  const USER_AGENT: "User-Agent";
  const CACHE_CONTROL: "Cache-Control";
  const IF_MODIFIED_SINCE: "If-Modified-Since";
  const ETAG: "ETag";
}

Error Handling

HTTP error handling and network exception management.

/**
 * HTTP error interface
 */
interface HttpError extends Error {
  response?: HttpResponse;
  statusCode?: number;
  responseText?: string;
}

/**
 * Network error types
 */
namespace HttpErrorType {
  const TIMEOUT: "timeout";
  const NO_CONNECTION: "no_connection";
  const SERVER_ERROR: "server_error";
  const CLIENT_ERROR: "client_error";
  const PARSE_ERROR: "parse_error";
}

Error Handling Examples:

import { Http } from "tns-core-modules";

class ApiClient {
  private baseUrl: string;
  private authToken: string;
  
  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }
  
  async get<T>(endpoint: string): Promise<T> {
    try {
      const response = await Http.request({
        url: `${this.baseUrl}${endpoint}`,
        method: "GET",
        headers: this.getHeaders(),
        timeout: 10000
      });
      
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return response.content.toJSON();
      } else {
        throw this.createHttpError(response);
      }
    } catch (error) {
      console.error(`API GET error for ${endpoint}:`, error);
      throw this.handleNetworkError(error);
    }
  }
  
  async post<T>(endpoint: string, data: any): Promise<T> {
    try {
      const response = await Http.request({
        url: `${this.baseUrl}${endpoint}`,
        method: "POST",
        headers: {
          ...this.getHeaders(),
          "Content-Type": "application/json"
        },
        content: JSON.stringify(data),
        timeout: 15000
      });
      
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return response.content.toJSON();
      } else {
        throw this.createHttpError(response);
      }
    } catch (error) {
      console.error(`API POST error for ${endpoint}:`, error);
      throw this.handleNetworkError(error);
    }
  }
  
  private getHeaders(): Headers {
    const headers: Headers = {
      "Accept": "application/json",
      "User-Agent": "NativeScript-App/1.0"
    };
    
    if (this.authToken) {
      headers["Authorization"] = `Bearer ${this.authToken}`;
    }
    
    return headers;
  }
  
  private createHttpError(response: HttpResponse): HttpError {
    const error = new Error(`HTTP ${response.statusCode}`) as HttpError;
    error.response = response;
    error.statusCode = response.statusCode;
    error.responseText = response.content.toString();
    return error;
  }
  
  private handleNetworkError(error: any): Error {
    if (error.message?.includes("timeout")) {
      return new Error("Request timeout - please check your connection");
    } else if (error.message?.includes("network")) {
      return new Error("Network error - please check your internet connection");
    }
    return error;
  }
  
  setAuthToken(token: string): void {
    this.authToken = token;
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-tns-core-modules

docs

application.md

data-binding.md

file-system.md

http-client.md

image-handling.md

index.md

platform-utils.md

ui-components.md

tile.json