前提
在前后端联调的时候总会牵扯到一个问题,就是参数的传递方式,GET请求就不说了,参数往url后面一拼,万事大吉。
然而一到POST请求的时候,花样就来了,后端童鞋跟你说,我这个接口在postman试过是没问题的,你content-type设置成我要的就行了,要是真这么简单今天咱也就啥也不写了。
今天就来聊聊设置不同content-type时,前端童鞋的参数设置方式,以及在http中是什么样的,以及后端是怎么接受的。
content-type的值非常非常多,有兴趣的去查一下 HTTP Content-type 对照表,我们今天只谈POST请求 request headers中的content-type
准备工作
前端: fetch; 字符集设置: charset=utf-8
抓包工具: charles; 浏览器: chrome
node服务: Koa; 后端: SpringBoot
简单封装post
export const post = (url: string, params: any, options: any = {}) => {
return fetch(url, {
method: 'post',
headers: {
...options.headers,
},
body: params
});
}
node服务
import router from './router/index'; // 路由配置,无关紧要
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody({
multipart: true
}));
app.use(async (ctx, next) => {
console.log(ctx.request.headers);
console.log('body', { ...ctx.request.body }); // 主要看一下打印出的body
ctx.params = {
...ctx.request.body,
...ctx.query
};
await next();
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000)
text/plain
首先就是con