【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))
相关推荐
大鹏说大话2 分钟前
和小鹅通相近的知识付费小程序平台有哪些
开发语言
Dovis(誓平步青云)6 分钟前
启元 T1 Pro 视觉伺服实践:基于 HSV 阈值与针孔测距的启元机器人寻物实现
开发语言·人工智能·机器学习·二次开发
Ryan-Zhong18 分钟前
数字人口播视频 API 实战:Python 跑通模板合成、异步轮询与批量出片
开发语言·python·音视频
努力努力再努力wz21 分钟前
【Lua 入门系列】模块与包(一):从多文件组织到require 运行时加载机制、模块缓存、预加载搜索与 Lua 文件搜索机制
开发语言·junit·lua
fengci.26 分钟前
CTF2困难部分
开发语言·网络·python·安全·php
佳得动27 分钟前
编译和链接的认识(C语言)
c语言·开发语言
程序员大阳36 分钟前
副队长JavaScript教程(67)-Ajax初识:背景、历史与核心概念
javascript·ajax·同步·异步·概念·背景·来是
大黄说说38 分钟前
PHP 异步怎么实现?Swoole、Workerman 使用场景对比
开发语言·php·swoole
十二同学啊38 分钟前
Python 工程化详解:项目结构、依赖管理、代码质量、测试与部署
java·开发语言·python