【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))
相关推荐
froginwe1111 分钟前
R 基础运算
开发语言
醉城夜风~11 分钟前
[数据结构]堆详解
开发语言·数据结构
堕落年代15 分钟前
Vue主流的状态保存框架对比
前端·javascript·vue.js
没资格抱怨16 分钟前
el-pagination的使用说明
javascript·vue.js·elementui
冴羽26 分钟前
Svelte 最新中文文档教程(22)—— Svelte 5 迁移指南
前端·javascript·svelte
青红光硫化黑35 分钟前
React基础之useEffect
javascript·react.js·ecmascript
17´38 分钟前
Qt从入门到入土(八) -打包Qt程序
开发语言·c++·qt
AI+程序员在路上39 分钟前
QT显示网页控件QAxWidget、QWebEngineView及区别
开发语言·qt
bin915342 分钟前
DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加列宽调整功能,示例Table14基础固定表头示例
前端·javascript·vue.js·ecmascript·deepseek
南玖yy44 分钟前
C语言柔性数组深度解析:动态内存管理的艺术
c语言·开发语言·柔性数组