ReactNative踩坑日志——fetch如何向服务器传递参数


一:简单参数

    简单的参数,我们可以使用手动拼接的方式传递。

    格式为:

fetch(url?key1=val1&key2=val2&...).then((response) => response.json())
            .then((json) => {
                //处理返回值
            }).catch((error) => {
             //异常处理
        })

 

二:POST方法传递数据,在fetch方法的参数中定义post方法的参数们:method、headers、body

fetch(url', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'secondValue',
  })
})

 

三:复杂表单数据的传递,比如图片等

我们可以自己new一个FormData,直接传给body,在FormData中传递字节流实现上传图片的功能。 

let formData = new FormData();  
formData.append("key",表单内容);  

  
fetch(url , {  
 method: 'POST',  
 headers: {},  
 body: formData,  
).then((response) => {  
 if (response.ok) {  
     return response.json();  
 }  
).then((json) => {  
 alert(JSON.stringify(json));  
).catch((error) => {  
 console.error(error);  
);  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM