POST 請求的三種常見數(shù)據(jù)提交格式 - SegmentFault 思否
post請求:
params:放在請求的url里,后臺用@RequestParam接收
body:放在請求的body里,后臺接收方式分別如下:
- Content-Type:x-www-form-urlencoded:@RequestParam接收到的是value值 @RequestBody是接收到的鍵值對
- Content-Type:multipart/form-data:@RequestParam、@RequestBody、@RequestPart 均可
- Content-Type:application/json:@RequestBody才行
1)表單放params里:若后端使用@RequestParam 來接收前端傳過來的參數(shù)的,Content-Type要設置為application/x-www-form-urlencoded,并且需要對data使用qs.stringify換成鍵值對的形式;參數(shù)放在url?body里進行傳遞
// @RequsetParam請求
const postRequestParam = (url, params, type) => {
let baseUrl = getBaseUrl(type);
return axios({
method: "post",
url: `${baseUrl}${url}`,
data: params,
transformRequest: [//放params里要將data轉為k=v&k1=v1(可以用qs庫qs.stringify)
function (data) {
let ret = "";
for (let it in data) {
ret +=
encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
return ret;
}
],
headers: {//放params里要將Content-Type設置為application/x-www-form-urlencoded
"Content-Type": "application/x-www-form-urlencoded"
}
});
};
2)json放body里:若后端使用@RequestBody 來接收前端傳過來的參數(shù)的,Content-Type要設置為application/json;參數(shù)放在body里進行傳遞? (axios默認放body)
// @RequestBody請求
const postRequestBody = (url, params) => {
return axios({
method: "post",
url: `${base}${url}`,
data: params,
headers: { //放body要時,Content-Tpye為application/json,默認值也是這個
"Content-Type": "application/json",
charset: "utf-8"
}
});
};
3)文件放body里:如果傳遞的是文件,需設置"Content-Type: multipart/form-data"
使用 FormData() 構造函數(shù),瀏覽器會自動識別并添加請求頭 "Content-Type: multipart/form-data"文章來源:http://www.zghlxwxcb.cn/news/detail-404924.html
實際上是放在body里傳遞的。文章來源地址http://www.zghlxwxcb.cn/news/detail-404924.html
const params = new FormData();
params.append('file', this.file);
axios.post({url,params})
//axios.post({url,data:params}) 即使不寫data,默認是data放body里
到了這里,關于POST請求的三種常見格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!