本文包罗了常见的发送网络请求的方法
XMLHttpReqest
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>案例_地区查询</title>
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
- <style>
- :root {
- font-size: 15px;
- }
- body {
- padding-top: 15px;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <form id="editForm" class="row">
- <!-- 输入省份名字 -->
- <div class="mb-3 col">
- <label class="form-label">省份名字</label>
- <input type="text" value="北京" name="province" class="form-control province" placeholder="请输入省份名称" />
- </div>
- <!-- 输入城市名字 -->
- <div class="mb-3 col">
- <label class="form-label">城市名字</label>
- <input type="text" value="北京市" name="city" class="form-control city" placeholder="请输入城市名称" />
- </div>
- </form>
- <button type="button" class="btn btn-primary sel-btn">查询</button>
- <br><br>
- <p>地区列表: </p>
- <ul class="list-group">
- <!-- 示例地区 -->
- <li class="list-group-item">东城区</li>
- </ul>
- </div>
- <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
- <script>
- /**
- * 目标: 根据省份和城市名字, 查询对应的地区列表
- */
- document.querySelector('.sel-btn').addEventListener('click',()=>{
- //收集省和市的值
- const pname= document.querySelector('.province').value
- const cname= document.querySelector('.city').value
- const obj={
- pname,
- cname
- }
- // URLSearchParams转化成查询参数
- const paramsObj=new URLSearchParams(obj)
- const queryString=paramsObj.toString()
- //使用xhr来查询对像
- const xhr=new XMLHttpRequest()
- xhr.open('GET',`http://hmajax.itheima.net/api/area?${queryString}`)
- xhr.addEventListener('loadend',()=>{
- console.log(xhr.response)
- const data=JSON.parse(xhr.response)
-
- const htmlStr=data.list.map(areaName=>{
- return ` <li class="list-group-item">${areaName}</li>`
- }).join('')
- document.querySelector('.list-group').innerHTML=htmlStr
- })
- xhr.send()
-
- })
- </script>
- </body>
- </html>
复制代码- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <button class="reg-btn">注册账号</button>
- <style>
- .reg-btn{
- background-color: aquamarine;
- font-size: 20px;
- width: 120px;
- height: auto;
- border-radius: 20px;
- }
- </style>
- <script>
- document.querySelector('.reg-btn').addEventListener('click',()=>{
- const xhr=new XMLHttpRequest()
- xhr.open('POST','http://hmajax.itheima.net/api/register')
- xhr.addEventListener('loadend',()=>{
- console.log(xhr.response)
- })
- // 设置请求投-告诉服务器
- xhr.setRequestHeader('Content-Type','application/json')
- const useObj={
- username:'itheima006',
- password:'7654321'
- }
- const useStr=JSON.stringify(useObj)
- //携带请求体数据
- xhr.send(useStr)
- })
-
- </script>
- </body>
- </html>
复制代码 promise
封装axios
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <p class="my-p"></p>
- <script>
- function myaxios(object){
- return new Promise((resolve,reject)=>{
- const xhr=new XMLHttpRequest()
- if(object.params){
- //支持参数传递
- const paramsObj=new URLSearchParams(object.params)
- const queryString=paramsObj.toString()
- //拼接参数
- object.url+=`?${queryString}`
- }
- xhr.open(object.method||'GET',object.url)
- xhr.addEventListener('loadend',()=>{
- if(xhr.status>=200&&xhr.status<300){
- resolve(JSON.parse(xhr.response))
- }
- else{
- reject(new Error(xhr.response))
- }
- })
-
- //判断是否有data,携带请求体
- // if(object.data){
- // //转化数字类型,在send中发送
- // const jsonStr=JSON.stringify(object.data)
- // xhr.setRequestHeader('Content-Type','application/json')
- // xhr.send(jsonStr)
- // }
- //没有请求体
- xhr.send()
- })
- }
- myaxios({
- url:'http://hmajax.itheima.net/api/area',
- method:'GET',
- params:{
- pname:'北京',
- cname:'北京市'
- },
-
- // data:{
- // username:'itheima005',
- // password:'565622'
- // }
-
- }).then(result=>{
- console.log(result)
- document.querySelector('.my-p').innerHTML=result.list.join('<br>')
- }).catch(error=>{
- document.querySelector('.my-p').innerHTML=error.message
- console.log(error)
- })
- </script>
- </body>
- </html>
复制代码 axios
async await
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>async函数和await_解决回调函数地狱</title>
- </head>
- <body>
- <form>
- <span>省份:</span>
- <select>
- <option class="province"></option>
- </select>
- <span>城市:</span>
- <select>
- <option class="city"></option>
- </select>
- <span>地区:</span>
- <select>
- <option class="area"></option>
- </select>
- </form>
- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- <script>
- /**
- * 目标:掌握async和await语法,解决回调函数地狱
- * 概念:在async函数内,使用await关键字,获取Promise对象"成功状态"结果值
- * 注意:await必须用在async修饰的函数内(await会阻止"异步函数内"代码继续执行,原地等待结果)
- */
- async function getDate() {
- try{
- const pObj=await axios({
- url:'http://hmajax.itheima.net/api/province',
- })
- const pname=pObj.data.list[0]
- console.log(pname)
- const cObj= await axios ({url:'http://hmajax.itheima.net/api/city',params:{pname}})
- const cname=cObj.data.list[0]
- console.log(pObj)
- console.log(cname)
- const areaObj=await axios({url:'http://hmajax.itheima.net/api/area',params:{pname,cname}})
- const anaem=areaObj.data.list[0]
- console.log(anaem)
-
- document.querySelector('.province').innerHTML=pname
- document.querySelector('.city').innerHTML=cname
- document.querySelector('.area').innerHTML=anaem
- }catch(error){
- console.dir(error)
- }
-
-
- }
- getDate()
-
- </script>
- </body>
- </html>
复制代码 提交图片案例
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>图片上传</title>
- </head>
- <body>
- <!-- 文件选择元素 -->
- <input type="file" class="upload">
- <img src="" alt="" class="my-img">
- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- <script>
- /**
- * 目标:图片上传,显示到网页上
- * 1. 获取图片文件
- * 2. 使用 FormData 携带图片文件
- * 3. 提交到服务器,获取图片url网址使用
- */
- document.querySelector('.upload').addEventListener('change',e=>{
- console.log(e.target.files[0])
- //使用formDate携带文件
- const fd=new FormData()
- fd.append('img',e.target.files[0])
- //axios提交到服务器
- axios({
- url:'http://hmajax.itheima.net/api/uploadimg',
- method:'POST',
- data:fd
-
- }).then(result=>{
- const myimg=result.data.data.url
- document.querySelector('.my-img').src=myimg
- })
- })
- </script>
- </body>
- </html>
复制代码 axios请求拦截器和响应拦截器
- import axios from 'axios'
- import { useUserStore } from '@/stores/userStore'
- import router from '@/router'
- const httpInstance=axios.create({
- baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net',
- timeout:10000
- })
- //拦截器
- //axios拦截器
- httpInstance.interceptors.request.use(config=>{
-
- //从pinia获取token数据
- const userStore=useUserStore()
- //按照后端的要求拼接token数据
- const token=userStore.userInfo.token
- if(token){
- config.headers.Authorization=`Bearer ${token}`
- }
- return config
- },e=>Promise.reject(e))
- //axios响应式拦截器
- httpInstance.interceptors.response.use(res=>res.data,e=>{
- //错误提示
- ElMessage({
- type:'warning',
- message:e.response.data.message
- })
- //401token失效处理
- //清除本地用户数据
- //跳转到登录页
- const userStore=useUserStore()
- if(e.response.status===401){
- userStore.clearUserInfo()
- router.push('/login')
- }
- return Promise.reject(e)
- })
- export default httpInstance
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |