【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))
相关推荐
十年Java程序媛5 分钟前
JVM 基础与 GC 垃圾回收详解|可达性分析、分代模型、垃圾收集器、STW
java·开发语言·jvm·spring boot·后端·面试
估值探索者7 分钟前
【Python量化选股流水线 #03】候选股怎么排序?动量+低波+流动性三因子打分取 Top-N
开发语言·python·接口·api接口·股票数据接口·数据接口·股票数据api接口
骑士雄师7 分钟前
supervisor 中关于上下文多轮信息维护常用到的python语法
开发语言·python
曹牧16 分钟前
C#:字符串占位符与值数量不一致
开发语言·数据库·c#
只睡四小时24 分钟前
Local-First 数据契约:一张表装下 4 类数据
前端·javascript·架构设计·local-first·数据契约
迅猛龙办公室25 分钟前
Python函数实现反转一个只有3位数的整数
开发语言·前端·python
“AI国潮设计-小江”27 分钟前
《【AIGC实战】Python+SDXL批量生成“英歌舞树莓香草布丁”IP,附保持角色一致性的代码逻辑》
开发语言·人工智能·python·prompt·aigc
闻缺陷则喜何志丹33 分钟前
【C++特性及类库】多线程
开发语言·c++·多线程·语言特性·系统库
dtq04241 小时前
C++3 - 分支语句if和string变量
开发语言·c++·学习
jimy11 小时前
c++类成员访问只看静态类型
开发语言·c++