后端代码
- 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);
})
复制代码