整理下初学时做过的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('小刘的服务器')
})