Demo1
server
router.get('/api/one', function (req, res, next) {
res.end('hello, itLike!');
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function () {
var btn = document.getElementById('send');
btn.onclick = function () {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open('get', 'http://localhost:3000/api/one', true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
var status = xhr.status;
if (status === 200) {
console.log(xhr.response);
}
}
}
}
}
</script>
</head>
<body>
<button id="send">发送一个请求</button>
</body>
</html>
Demo2
server
router.get('/api/two', function (req, res, next) {
console.log(req.query);
res.end('ccc');
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function () {
var btn = document.getElementById('send');
btn.onclick = function () {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var account = document.getElementById('account').value;
var pwd = document.getElementById('pwd').value;
xhr.open('get', 'http://localhost:3000/api/two?account=' + account + '&pwd=' + pwd + '&random=' + getRandomStr(), true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
}
function getRandomStr() {
return Math.random() + (new Date()).getTime();
}
</script>
</head>
<body>
<input id="account" type="text" name="account">
<input id="pwd" type="text" name="pwd">
<button id="send">发送一个请求</button>
</body>
</html>
Demo3: get request Package
Demo4: optimization. Long setting request URI encoding and
Demo5: Simple Post
Demo6: GET and POST package