$.ajax({
url:'http://localhost:7777/charts/query',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"cccc":"32423423"}),
dataType: 'json',
success:function (resp) {
console.log(resp.models);
}
})
const Koa = require('koa')
const app = new Koa()
app.use( async (ctx) => {
ctx.body = {
url: ctx.url,
ctx_query: ctx.query,
ctx_querystring: ctx.querystring
}
})
app.listen(3000, () => {
console.log('start ok')
})
npm install koa-bodyparser --save
onst Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const app = new Koa()
app.use(bodyParser())
app.use( async (ctx) => {
ctx.body = ctx.request.body
})
app.listen(3000, () => {
console.log('start ok')
})
//使用原生方式
const Koa = require('koa')
const app = new Koa()
app.use( async (ctx) => {
let data = await parseData(ctx)
ctx.body = data
})
app.listen(3000, () => {
console.log('start ok')
})
function parseData(ctx) {
return new Promise((resolve, reject) => {
try {
let str = ''
ctx.req.on('data', (data) => {
str += data
})
ctx.req.addListener('end', () => {
resolve(parseUrl(str))
})
} catch (err) {
reject(err)
}
});
}
function parseUrl(url) {
let obj = {}
let arr = url.split('&')
arr.forEach((e, i) => {
let temparr = e.split('=')
obj[temparr[0]] = temparr[1]
});
return obj
}
原生方法相对来说比较繁琐,所以一般采用简单版的方式,需要获取参数,只需调用request.body就可以获取到post请求的参数了