fetch的get和post传参

转自 https://blog.csdn.net/dylan_zeng92/article/details/75371034?utm_source=blogxgwz8

原生get请求是在网址链接后加上?key=value&key=value进行传参。原生fetch中一般用法为fetch(url,{配置}).then((res)=>{}).catch((res)=>{}); 
1、其中配置参数一般如下:

method:请求使用的方法,如:POST/GET 
  headers:请求头信息,可能是字符串,也有可能是Header对象 
   body:请求的body信息:可能是Blod/BufferSource/FormData/URLSearchParam或者是字符串;post中传参位置 
mode:请求模式:cors /no-cors/same-origin; 
credentials:请求的credentials 
cache:请求的cache模式:default,no-store,reload,no-cache,force-cache ,only-if-cached

2、then中返回的为一个promise对象 
属性:

res.status (number) - HTTP请求结果参数,在100–599 范围
            res.statusText (String) - 服务器返回的状态报告
            res.ok (boolean) - 如果返回200表示请求成功则为true
            res.headers (Headers) - 返回头部信息,下面详细介绍
            res.url (String) - 请求的地址
    方法:
            res.text() - 以string的形式生成请求text
            res.json() - 生成JSON.parse(responseText)的结果
            res.blob() - 生成一个Blob
            res.arrayBuffer() - 生成一个ArrayBuffer
            res.formData() - 生成格式化的数据,可用于其他的请求
    其他方法:
            clone()
            Response.error()
            Response.redirect()

 

 

实例化一个post传参类型fetch请求


//创建一个配置 
let options = { 
method: 'POST',//post请求 
headers: { 
'Accept': 'application/json', 
'Content-Type': 'application/json' 
}, 
body: JSON.stringify({//post请求参数 
name: 'Hubot', 
login: 'hubot', 
}) 

//新建一个fetch请求 
fetch('/users',options).then((res)=>{ 
if(res.ok){//如果取数据成功 
res.json().then((data)=>{ 
//转化为json数据进行处理 
console.log(data); 

}else{ 
console.log(res.status); 
//查看获取状态 

}).catch((res)=>{ 
//输出一些错误信息 
console.log(res.status); 
})

接下来解决一下get请求传参:
 

1、最简单的方法已知url中不带问号?


fetch(url + "?" + a,{ 
method:'get' 
}).then((res)=>{}).catch((res)=>{}) 

2、万能处理的方法,直接先封装一个函数去判断url中是否存在?
export function  get(url,params){  
        if (params) {  
            let paramsArray = [];  
            //拼接参数  
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))  
            if (url.search(/\?/) === -1) {  
                url += '?' + paramsArray.join('&')  
            } else {  
                url += '&' + paramsArray.join('&')  
            }  
        }  
        //fetch请求  
        fetch(url,{  
            method: 'GET',  
        })  
            .then((response) => {}).catch((error) => {  
                alert(error)  
            })  
    }  

此外fetch中间件fetchjsonp还可用于跨域

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 Fetch API 向 PHP 传参时,需要使用 POST 请求,并将参数附加在请求的 body 中。以下是一个简单的示例: ```javascript const data = { name: 'John', email: 'john@example.com' }; fetch('example.php', { method: 'POST', body: JSON.stringify(data) }).then(response => { console.log(response); }); ``` 上面代码中,我们将一个包含 name 和 email 参数的对象 data 通过 POST 请求发送到 example.php 文件中。在请求中,我们通过 JSON.stringify() 方法将 data 对象转换成 JSON 字符串,然后将其附加在请求的 body 中。在 PHP 中可以使用上面提到的方法来接收这个请求并获取参数。 需要注意的是,如果你没有在请求头中设置 Content-Type 为 application/json,PHP 默认会将请求体作为 application/x-www-form-urlencoded 类型处理。此时,你需要使用 $_POST 来获取参数,或者使用 parse_str() 方法将请求体解析成数组,例如: ```php // 使用 $_POST 获取参数 $name = $_POST['name']; $email = $_POST['email']; // 或者使用 parse_str() 方法 parse_str(file_get_contents("php://input"), $data); $name = $data['name']; $email = $data['email']; ``` 如果你希望将请求体以 JSON 格式传递到 PHP 中,需要在请求头中显式地设置 Content-Type 为 application/json,例如: ```javascript const data = { name: 'John', email: 'john@example.com' }; fetch('example.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(response => { console.log(response); }); ``` 这样,在 PHP 中就可以使用 file_get_contents('php://input') 方法获取原始请求体,并使用 json_decode() 方法解析 JSON,例如: ```php $json = file_get_contents('php://input'); $data = json_decode($json); $name = $data->name; $email = $data->email; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值