Hi老师,根据您给的解决方案,还是报错,错误为400
来源:3-9 .网络层框架HiNet设计与开发-下
慕尼黑0536602
2022-02-10
hi 老师,我的get 封装后没有问题,但是post有问题,报错是:400 ,
您可以看下是代码哪里出问题吗??谢谢:
export function post(api:string){
return (params:{}) =>{
return async (queryParams?: {} | string) => {
const { headers, url } = Constants;
var data, cType;
if(params instanceof FormData) {
data = params;
cType ='multipart/form-data'
}else{
data = JSON.stringify(params);
cType = 'application/json';
}
return handleData(fetch(buildParams(url+api,queryParams),
{
method:'POST',
body:data,
headers:{
'content-type':cType,
...headers,
}
}
))
}
}
}
/**
* 处理接口返回数据
* @param doAction
*/
function handleData(doAction:Promise<any>){
return new Promise((resolve,reject)=>{
doAction.then((res)=>{
//解析Content-Type 防止非json数据进行Json转换
const type= res.headers.get('Content-Type');
if((type||'').indexOf('json') !== -1){
return res.json();
}
return res.text();
}).then((result)=>{
console.log(JSON.stringify(result));
if(typeof result ==="string"){
throw new Error(result);
}
const{code,msg,data:{list = undefined}={}} = result;
if(code === 401){
//跳转到登录页
}
resolve(list||result);
}).catch((error)=>{
reject(error);
})
});
}
/**
* 构建URL参数
* @param url
* @param params
* @returns
*/
function buildParams(url:string,params?:{}|string):string{
let newUrl = new URL(url),finalUrl;
if(typeof params === 'object'){
for(const [key,value] of Object.entries(params)){
newUrl.searchParams.append(key,value as string);
}
finalUrl = newUrl.toString();
}else if(typeof params === 'string'){
//适配path
finalUrl = url.endsWith('/')?url+params:+"/"+params;
}else{
finalUrl = newUrl.toString();
}
console.log("我们最终获得的finalUrl:",finalUrl);
return finalUrl;
}
下面 是我的应用:
const doPost = () =>{
const formData = new FormData();
formData.append('requestParams','RN');
post(Constants.test.api)(formData)().then(result=>{
setTxt(JSON.stringify(result));
}).catch(e=>{
console.log(e);
});
}
写回答
2回答
-
报错是因为requestPrams没有传递过去导致的,你将课程源码copy过来运行看还报不报这个错误呢
112022-02-10 -
慕尼黑0536602
提问者
2022-02-10
补充:我收到的错误:
我们最终获得的finalUrl: https://api.devio.org/uapi/test/test/
LOG {"timestamp":"2022-02-09T23:31:34.116+0000","status":400,"error":"Bad Request","message":"Required String
parameter 'requestPrams' is not present","path":"/uapi/test/test/"}
00
相似问题