You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求非Angular环境下TypeScript发送JSON格式HTTP Post请求示例

没问题!我知道找非Angular的TypeScript HTTP POST示例确实容易搜到框架相关的,给你两个实用的方案,都是专门处理JSON请求和响应的:

非Angular的TypeScript HTTP POST请求示例

1. 使用浏览器原生Fetch API(无需额外依赖)

现代浏览器原生支持Fetch API,TypeScript对它的类型兼容很好,完全不需要安装任何库就能实现需求。这里我加上了TypeScript的类型定义,让代码更安全:

// 定义请求数据的类型,让TS帮你做类型检查
interface RequestData {
  username: string;
  email: string;
}

// 定义响应数据的类型,避免后续处理时的类型模糊
interface ResponseData {
  success: boolean;
  message: string;
  userId?: number;
}

async function postData(url: string, data: RequestData): Promise<ResponseData> {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 如果API需要身份验证,这里可以加Authorization头
        // 'Authorization': 'Bearer your-access-token'
      },
      body: JSON.stringify(data) // 把TypeScript对象转成JSON字符串
    });

    // 检查HTTP响应状态码,处理4xx/5xx错误
    if (!response.ok) {
      throw new Error(`请求失败!状态码: ${response.status}`);
    }

    // 把响应解析成我们定义好的类型
    const responseJson = await response.json() as ResponseData;
    return responseJson;
  } catch (error) {
    console.error('请求出错:', error);
    throw error; // 把错误抛出去让调用方自行处理
  }
}

// 调用示例
const userData: RequestData = {
  username: 'johndoe',
  email: 'john@example.com'
};

postData('https://your-api-url.com/users', userData)
  .then(result => {
    console.log('请求成功:', result);
    // 这里可以根据返回结果做UI更新等操作
  })
  .catch(error => {
    console.error('处理请求错误:', error);
  });

2. 使用Axios(轻量HTTP库,更简洁的API)

如果你觉得原生Fetch的错误处理和语法有点繁琐,可以试试Axios——这是个非常流行的轻量HTTP库,自动帮你处理JSON解析,错误逻辑也更清晰。

首先需要安装Axios:

npm install axios

然后是TypeScript示例:

import axios from 'axios';

// 同样定义请求和响应的类型
interface RequestData {
  username: string;
  email: string;
}

interface ResponseData {
  success: boolean;
  message: string;
  userId?: number;
}

async function postWithAxios(url: string, data: RequestData): Promise<ResponseData> {
  try {
    // Axios直接支持泛型,指定响应类型后自动解析
    const response = await axios.post<ResponseData>(url, data, {
      headers: {
        'Content-Type': 'application/json',
        // 同样可以添加Authorization等自定义头
      }
    });
    return response.data; // Axios已经帮你把响应转成JSON了,直接取data即可
  } catch (error) {
    // 专门处理Axios的错误,能拿到更详细的响应信息
    if (axios.isAxiosError(error)) {
      console.error('请求错误详情:', error.response?.data || error.message);
    } else {
      console.error('未知错误:', error);
    }
    throw error;
  }
}

// 调用示例
const userData: RequestData = {
  username: 'janedoe',
  email: 'jane@example.com'
};

postWithAxios('https://your-api-url.com/users', userData)
  .then(result => {
    console.log('Axios请求成功:', result);
  })
  .catch(error => {
    console.error('Axios请求失败:', error);
  });

额外小提示

  • 如果是在Node.js环境下写TypeScript,Node 18+已经原生支持Fetch API,低版本可以安装node-fetch包,用法和浏览器Fetch几乎一致;
  • TypeScript的类型定义是可选的,但加上后能避免很多拼写错误和类型不匹配的问题,推荐使用。

内容的提问来源于stack exchange,提问作者Derek Lawrence

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:29:55