fetch is used to replace the promise-based design of XMLHttpRequest!
Simple usage is as follows:
fetch("/fetch1", {
method:"post",
headers:{
"content-type": "application/json"
},
body:JSON.stringify({name:"scy"})
}).then(res => res.text()).then(result => p.innerText = result);
The first parameter is the url
and the second parameter can be written like this:
var head = new Headers();
head.append("Content-Type", "text/plain");
...
var mInit = {
method: "POST",
headers: head
};
fetch("url", mInit)...
There are many properties:
- method Request method POST/GET, etc.
- url the requested address
- headers request header (can be a Headers object or a JSON object)
- context request context
- referrer specifies the request source address
- mode The mode of the request (is it cross-domain cors or normal request no-cors)
- credentials Whether to carry cookie information in cross-origin requests (omit cross-origin carry/same-origin same-origin carry)
- redirect redirect
- integrity A hash value used to verify the integrity of the requested resource MDN
- cache whether to cache this request
Example
front-end fetch.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>fetch的用法</title>
<style media="screen">
.container{
width:800px;
height:600px;
margin: 0 auto;
}
span{
display: inline;
color: red;
}
</style>
</head>
<body>
<form class="container" method="post">
<input type="text" name="name" value="13699999999" placeholder="请输入手机号"><span class="name_error"></span><br>
<input type="text" name="password" value="" placeholder="请输入6-12位的密码"><span class="pwd_error"></span><br>
<input type="submit" name="" value="注册" style="width:180px; background-color:SkyBlue;height:32px">
</form>
<script type="text/javascript" src="javascripts/validate.js"></script>
<script type="text/javascript">
const form = document.querySelector("form");
const name_error = form.querySelector(".name_error");
const pwd_error = form.querySelector(".pwd_error");
form.onsubmit = function (event) {
event.preventDefault();
name_error.innerText = "";
pwd_error.innerText = "";
let n = form.querySelector("input[name=name]");
var name =n .value;
let ps = form.querySelector("input[name=password]");
var password = ps.value;
let errors = validate(name, password);
if (errors) {
showError(JSON.stringify(errors));
}else {
request(name, password);
}
}
function request(name, password) {
fetch("/re",{
method:"POST",
body:JSON.stringify({name, password}),
headers:{
"Content-Type":"application/json"
}
})
.then(res => res.text())
.then(errors => {
showError(errors)
})
}
function showError(errors) {
if (errors) {
errors = JSON.parse(errors);
if (errors.name) {
name_error.innerText = errors.name;
}
if (errors.password) {
pwd_error.innerText = errors.password;
}
}
else {
alert("SUCCESS!!!")
}
}
</script>
</body>
</html>
background fetch.js
const router = require("express").Router();
const validate = require("../public/javascripts/validate");
router.post("/re", function (req, res) {
const {name, password} = req.body;
console.log("validate(name, password)", validate(name, password));
res.send(validate(name, password));
});
module.exports = router;
A piece of verification code common to both ends validate.js
function validate(name, password) {
let errors = "";
if (!(/(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}/.test(name))) {
errors = errors || {};
errors.name = "手机格式不正确";
}
if (password.length < 6 || password.length > 12) {
errors = errors || {};
errors.password = "请输入最小6位、最大12位的密码";
}
console.log(errors);
return errors;
}
//确保只有后台才会调用这段代码
if(typeof window === "undefined")
module.exports = validate;