Skip to content

Commit

Permalink
新增例子:状态检查、设置首部
Browse files Browse the repository at this point in the history
  • Loading branch information
chyingp committed Dec 4, 2017
1 parent 6e92339 commit b88d407
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
8 changes: 8 additions & 0 deletions demo/2017.12.04-fetch/app.js
Expand Up @@ -48,6 +48,14 @@ app.get('/api/cors', cors(), function (req, res, next) {
res.end('ok');
});

app.get('/api/setting-request-header', function (req, res, next) {
res.end(req.headers['x-my-header']);
});

app.get('/api/check_state', function (req, res, next) {
res.sendStatus(req.query.status);
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
Expand Down
9 changes: 9 additions & 0 deletions demo/2017.12.04-fetch/routes/page.js
Expand Up @@ -23,4 +23,13 @@ router.get('/cors', function(req, res, next) {
res.render('cors');
});

router.get('/setting-request-header', function(req, res, next) {
res.render('setting-request-header');
});

router.get('/check-state', function(req, res, next) {
res.render('check-state');
});


module.exports = router;
33 changes: 33 additions & 0 deletions demo/2017.12.04-fetch/views/check-state.ejs
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<title>请求返回状态判断</title>
<meta charset="utf8">
</head>
<body>
<h1>请求返回状态判断</h1>
<p>服务端返回的内容: <span id="result"></span></p>

<script>
function doFetch (status) {
fetch('/api/check_state?status=' + status)
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error(`${response.statusText}${response.status}`);
}
})
.then(result => {
console.log(`成功啦!返回结果:${result}`);
})
.catch(error => {
console.log(`出错啦!出错原因:${error.message}`);
});
}
doFetch(200);
doFetch(404);
</script>
</body>
</html>
25 changes: 25 additions & 0 deletions demo/2017.12.04-fetch/views/setting-request-header.ejs
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<title>设置请求首部</title>
<meta charset="utf8">
</head>
<body>
<h1>设置请求首部</h1>
<p>服务端返回的内容: <span id="result"></span></p>

<script>
var options = {
headers: {
'X-MY-HEADER': 'X-MY-VALUE'
}
};
fetch('/api/setting-request-header', options)
.then(response => response.text())
.then(result => {
console.log(`result is : ${result}`);
});
</script>
</body>
</html>

0 comments on commit b88d407

Please sign in to comment.