使用koa处理前端发送的http请求

后端代码

  • 这里使用koa-body获取post请求的数据
  • koa-body可以处理三种类型的请求
    • multipart/form-data
    • application/x-www-urlencoded
    • application/json
const Koa = require('koa')
const app = new Koa()
const koaBody = require('koa-body')

app.use(koaBody())

app.use(ctx => {
  ctx.set('Access-Control-Allow-Origin', `*`)
  console.log('type', ctx.request.type)
  console.log(ctx.request.body)
  ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)}`
})

app.listen(3000)
复制代码
  • 这样写在前端浏览器中请求会报错,需要再加上
  ctx.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
复制代码

前端代码

/* 
jquery
默认的content-type是application/x-www-form-urlencoded,
当content-type是application/json时需要把参数转换为json字符串
*/
$.ajax({
 type:'post',
 url:'http://localhost:3000',
 contentType: "application/json",
data:JSON.stringify({
 a:123
}),
 success:res=>{
   console.log(res);
 },
 error:err=>{
   console.log(err)
 }
})
/* axios
默认的content-type是application/json,
当content-type是x-www-form-urlencoded时需要把参数转换为字符串传递如`a=1&b=2`
*/
axios.post('http://localhost:3000', {
   firstName: 'Fred',
   lastName: 'Flintstone'
 })
 .then(function (response) {
   console.log(response)
 })
 .catch(function (error) {
   console.log(error)
 })
 /*fetch 
 默认的content-type是 text/plain,
 当content-type是x-www-form-urlencoded时需要把参数转换为字符串传递如`a=1&b=2`,
 当content-type是application/json时需要把参数转换为json字符串
 */
fetch('http://localhost:3000', {
 method: 'POST',
 headers: {
   'Content-Type': 'application/json'
 },
 body: JSON.stringify({
   name: 'Hubot',
   login: 'hubot',
 })
}).then(res=>{
 console.log(res);
})
复制代码

转载于:https://juejin.im/post/5b1a1b0ce51d4506825f1760

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值