2021-07-05 ajax发送请求

ajax发送get请求

前台:

let xhr=new XMLHttpRequest();
xhr.open("get",`/check?username=${this.username}`,true);
xhr.onload=function(){
  //后台返回的数据(ctx.body)
  console.log(xhr.responseText)
}
xhr.send()

后台:

router.get("/check",(ctx,next)=>{
	//接收querystring形式的参数
	console.log(ctx.query.username);
})

ajax发送post请求

前台:

let xhr=new XMLHttpRequest();
xhr.open("post","/checkuser",true);
xhr.onload=function(){
  //后台返回的数据(ctx.body)
  console.log(xhr.responseText)
}
//设置请求头(默认,上传数据)
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
//上传文件时请求头(二进制编码)
xhr.setRequestHeader("Content-Type","multipart/form-data")
//json格式
xhr.setRequestHeader("Content-Type","application/json")
//post请求的参数
let data="username=张三&age=15"
xhr.send(data)

后台:

const koabody=require("koa-body")
app.use(koabody());
router.post('/checkuser',(ctx,next)=>{
	console.log(ctx.request.body);
})

文件上传

前台:

document.querySelector("button").click=function(){
	let file=document.querySelector(".myfile").files[0];
	//组装form
	let form=new FormData();
	form.append("img",file);
	form.append("name","张三");
	let xhr=new XMLHttpRequest();
	//文件上传使用post请求
	xhr.open("post",`/upload`,true);
	xhr.onload=function(){
	  //后台返回的数据(ctx.body)
	  console.log(xhr.responseText)
	}
	xhr.send(form);
}

后台:

const fs=require("fs");
app.use(koabody({
	//设置允许接收文件
	multipart:true
}))
router.post('/upload',(ctx,next)=>{
	console.log(ctx.request.body);
	console.log(ctx.request.files.img);
	//使用fs模块做转存
	let fileData=fs.readFileSync(ctx.request.files.img.path);
	fs.writeFileSync("imgs/"+ctx.request.files.img.name,fileData);
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值