【JavaScript】网络请求

原生 ajax

js 复制代码
// POST
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send('{"name":"xxx","age":"xxx"}');
xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
}
js 复制代码
 // GET
const xhr = new XMLHttpRequest();
// 地址后可以拼接 ?name=xxx&age=xxx 的参数
xhr.open('GET', 'http://localhost:3000');
xhr.send();
xhr.onreadystatechange = function () {
  if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
}

axios

js 复制代码
// get 请求
// .then 的形式
axios.get('http://127.0.0.1:8080/api/getData', {
  // 可以携带参数
  params: {
    id: 1
  }
}).then(res => {
  console.log(res.data)
})
// async 的形式
async function getData() {
  const res = await axios.get('http://127.0.0.1:8080/api/getData')
  console.log(res.data)
}
getData()
js 复制代码
// post 请求
axios.post('http://127.0.0.1:8080/api/postData',{
  id: 1,
}).then(res => {
  console.log(res.data)
})
js 复制代码
// axios 其他配置
const ins = axios.create({
  baseURL: 'http://127.0.0.1:3000',
  timeout: 5000
})
// 请求拦截器
ins.interceptors.request.use(config => {
  console.log("发送了请求")
  return config
})
// 响应拦截器
ins.interceptors.response.use(res => {
  console.log("响应了")
  return res
})
const getData = () => {
  ins.get('/get').then(res => {
    console.log(res)
  })
}
const postData = () => {
  ins.post('/post', {
    name: 'zs',
    age: 18
  }).then(res => {
    console.log(res)
  })
}
getData()
postData()

fetch API

js 复制代码
// fetch API 请求(默认get)
fetch('http://127.0.0.1:8080/api/getData')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
// post
fetch('http://127.0.0.1:8080/api/postData', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'xxx',
    age: 18
  })
})
  .then(response => {
    if (response.ok) {
      return response.json()
    }
  })
  .then(data => console.log(data))
  .catch(error => console.error(error))
相关推荐
李昊哲小课12 分钟前
Python 高级数据结构
开发语言·数据结构·python
Highcharts.js18 分钟前
Highcharts 使用指南Treegraph chart 树状图/结构树图|创建谱系图表、决策树、结构知识树等的图表工具
javascript·决策树·highcharts·图表开发·结构树·可视化图表库·谱系图表
局i21 分钟前
React 简单地图组件封装:基于高德地图 API 的实践(附源码)
前端·javascript·react.js
MediaTea21 分钟前
Python:词频统计流程及综合示例
开发语言·python
wregjru23 分钟前
【读书笔记】Effective C++ 条款5~6:若不想使用编译器自动生成的函数,就该明确拒绝
java·开发语言
语戚27 分钟前
从 JVM 底层拆解:i++、++i、i+=1、i=i+1 的实现逻辑与坑点
java·开发语言·jvm·面试·自增·指令·虚拟机
喜欢喝果茶.29 分钟前
Qt MQTT部署
开发语言·qt
进击的尘埃33 分钟前
Service Worker + stale-while-revalidate:让页面"假装"秒开的正经方案
javascript
wefg134 分钟前
【Linux】线程同步与互斥 - 2(线程同步/条件变量/基于阻塞/环形队列的cp模型/线程池/线程安全/读写锁)
linux·开发语言
yuki_uix35 分钟前
防抖(Debounce):从用户体验到手写实现
前端·javascript