使用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

你可能感兴趣的:(前端,json,后端)