【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))
相关推荐
apihz10 分钟前
域名WHOIS信息查询免费API使用指南
android·开发语言·数据库·网络协议·tcp/ip
coding随想23 分钟前
掌控网页的魔法之书:JavaScript DOM的奇幻之旅
开发语言·javascript·ecmascript
爱吃烤鸡翅的酸菜鱼42 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
然我1 小时前
不用 Redux 也能全局状态管理?看我用 useReducer+Context 搞个 Todo 应用
前端·javascript·react.js
前端小巷子1 小时前
Web 实时通信:从短轮询到 WebSocket
前端·javascript·面试
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己2 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090012 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
DanB242 小时前
html复习
javascript·microsoft·html
古月-一个C++方向的小白7 小时前
C++11之lambda表达式与包装器
开发语言·c++