1.利用ajax和express实现前后端交互

整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦

ajax.html
用原生js封装ajax

  • 实现get格式上传请求数据
  • 实现post格式上传请求数据
  • 实现中断请求
  • 缺点:由于时间问题没封装成 promise
<p></p>
  <script>
    let p = document.querySelector('p')
    ajax(
      {
        // url:'http://music.cpengx.cn/banner',
        url:"http://localhost:3000",
        type:"post",
        data:{type:0},
        timeout:1000,//设置超时事件
        success:(xmlhttp)=>{
          p.innerText = xmlhttp.responseText
        },
        error:(xmlhttp)=>{
          console.log(xmlhttp.status)
        }
      }
    )
    function ajax(option){
      let xmlhttp,timer
      if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest()
      }else{
        xmlhttp = new ActiveXObject()
      }
      if(option.type.toLowerCase() === "get"){
        xmlhttp.open("GET",option.url+"?"+objStr(option.data),true)
        xmlhttp.send()
      }else if(option.type.toLowerCase() === 'post'){
        xmlhttp.open("POST",option.url,true)
        xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xmlhttp.send(objStr(option.data))
      }
      xmlhttp.addEventListener('readystatechange',function(){
        if(xmlhttp.readyState ===4){
          clearTimeout(timer)
          if(xmlhttp.status >=200 && xmlhttp.status < 300){
            option.success(xmlhttp)
          }else{
            option.error(xmlhttp)
          }
        }
      })
      if(option.timeout){
        timer = setTimeout(()=>{
          console.log('连接中断了')
          xmlhttp.abort();
          clearTimeout(timer)
        },option.timeout)
      }
      function objStr(obj,res=[]){
        obj = obj ||{}
        if(typeof obj ==="string")return obj
        //IE:认为一个url只有一个结果,又是为了清楚浏览器的缓存
        obj.t = new Date().getTime()
        for(let key in obj){
          // url不能出现中文,需要转码
          res.push(encodeURIComponent(key) + '='+ encodeURIComponent(obj[key]))
        }
        return res.join("&")
      }
    }
  </script>

express.js
用node第三方包express搭建简易服务器

  • 实现接受get请求,返回响应数据
  • 实现接受post请求,返回响应数据
  • 实现静态服务
  • 实现跨域(服务端的跨域-真正的跨域)
const express = require('express')
let app = express()
// 自定义跨域中间件
var allowCors = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Credentials','true');
  next();
};
// 配置中间件(专门用来解析post请求体)
app.use(express.urlencoded({ extended: false }))
// parse application/json
app.use(express.json())

app.use(allowCors);//使用跨域中间件
app.get('/',(req,res)=>{
  console.log(req.query)
  console.log(req.body)
  res.send('get数据来了', req.query)
})
app.post("/",(req,res)=>{
  console.log(req.body)
  res.send(req.body)
})
//静态服务
app.use(express.static('../前后端交互/'))//文件夹
app.use('/ajax',express.static('./ajax.html'))//文件
app.listen(3000,()=>{
  console.log('小刘的服务器')
})
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳晓黑胡椒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值