最近在进行前后端+一点点算法+本科课程学习的多线程状态,代价就是由于要干的事情太多以至于不知道要干嘛而形成死锁进入无限的摸鱼状态,所以写完这篇之后就先把前端学习放下,并适当减缓编程方面的学习比重.
而昨晚正好遇到了一个需要向后端发送请求的情况.就是将密码通过post表单发送给后端进行判断,毕竟密码这种东西不可能由前端判断吧.大家可以去看一下:http://beifen.elatis.cn/
而在使用原生js发送表单的时候遇到了一些问题.发送表单时会刷新一下页面,这就导致了无法正确登录.
所以只能使用异步请求来发送表单,而jQuery的$.ajax
我完全没学过,只好使用React的fetch
来进行了.
不说废话了,接下来就正式开始吧.
fetch的基本形式
fetch就是获取的意思,如果只是想要"请求一下",只要直接将url传给fetch即可
fetch("https://www.baidu.com/");
如果想要请求后端,就填上后端文件的所在位置
fetch("test.php");
实际上fetch有两个参数,只不过第二个参数可以缺省
然后我们当然不是没事请求一下后端玩的,一般请求后端是要将用户与网页交互的结果(如用户填的表单等)发送给后端,并由后端进行一些处理(存数据,返回给前端处理结果等)
想要请求的同时携带表单,就要给fetch传入第二个参数了.
首先看一下下面这个实例:
fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
其实就是一个json对象...
所有可选参数和说明如下:
# method: 请求使用的方法,如 GET、POST。
# headers: 请求的头信息,形式为 Headers 的对象或包含 ByteString 值的对象字面量。
# body: 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
# mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
# credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受 FederatedCredential 实例或是一个 PasswordCredential 实例。
# cache: 请求的 cache 模式: default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
# redirect: 可用的 redirect 模式: follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中,Chrome 47之前的默认值是 follow,从 Chrome 47开始是 manual。
# referrer: 一个 USVString 可以是 no-referrer、client或一个 URL。默认是 client。
# referrerPolicy: Specifies the value of the referer HTTP header. May be one of no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
# integrity: 包括请求的 subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
然而实际上只有两个是必要的,那就是method
和body
顺便有一个类可以帮我们生成一个表单数据:FormData
我们可以用它来存储键值对形式的数据
用法如下:
let formData = new FormData(); //创建一个FormData类
formData.append("password", password); //添加一个数据,key为'password',value为变量password的值
有了它,我们可以实现两行搞定一个表单
fetch("test.php", {
method: "POST",
body: formData,
})
发送完表单之后有时候我们需要进行一些额外操作,如接收后端返回的信息,获取错误编码等.
这时候就需要用到then和catch了
一般是写成这样的:
fetch(url,{
method:"POST",
//anyelse
}).then(function(res){
//dosomething
return res;
}).then(function(res){
//dosomething
}).catch(function(err){
console.log(err);
})
其中res是来自上一个then的返回值,或是fetch的返回值(第一个then或catch)
then的数量任意
而then和catch里面一般传入一个闭包函数来进行各种丧心病狂的处理
以下是一个实例:
fetch("judge.php", {
method: "POST",
body: formData,
}).then(function(res){
if(res.status != 200){
console.log("Error, status: " + res.status);
return;
}else{
console.log("Success, status: " + res.status);
return res;
}
}).then(function(res){
let ret = res.text();
console.log(ret);
return ret;
}).then(function(data){
let val = data.PromiseValue;
console.log(val);
}).catch(function(err){
console.log("Fetch Error: " + err);
});
Ꭲhanks for sharing уour thouցhts. I reɑlly аppreciate your efforts annd
I am waiting for your next write ups hanks once again.