/
restful.html
317 lines (284 loc) · 56.2 KB
/
restful.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<!DOCTYPE html><html class="theme-next pisces use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.9.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><link rel="apple-touch-icon" sizes="180x180" href="/images/icons/favicon-48.png?v=6.7.0"><link rel="icon" type="image/png" sizes="32x32" href="/images/icons/favicon-32.png?v=6.7.0"><link rel="icon" type="image/png" sizes="16x16" href="/images/icons/favicon-16.png?v=6.7.0"><link rel="mask-icon" href="/images/icons/logo.svg?v=6.7.0" color="#222"><link rel="alternate" href="/atom.xml" title="菠菜眾長" type="application/atom+xml"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/fancybox/source/jquery.fancybox.css" rel="stylesheet" type="text/css"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=6.7.0" rel="stylesheet" type="text/css"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Pisces",version:"6.7.0",sidebar:{position:"left",display:"always",offset:12,b2t:!1,scrollpercent:!0,onmobile:!0},fancybox:!0,fastclick:!0,lazyload:!0,tabs:!0,motion:{enable:!0,async:!0,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><meta name="baidu-site-verification" content="B2fOjPkYa7"><meta name="google-site-verification" content="OhdtVOx5uwpZ_mMm0AZJXzw-dY1PPpAAkdavmmQhIL4"><meta name="360-site-verification" content="5b1c9d7574859ca6e460dd687667d5dc"><meta name="shenma-site-verification" content="933461d02e7b7c40e5293ee90085127c_1569650330"><meta name="description" content="RESTful 是一種系統開發設計風格、原則。可視情況調整,以下參考來源 RFC5789 https://tools.ietf.org/html/rfc5789Noun一般資源通用於一律使用複數名詞例如:/books 或 /books/123。但有部分人認為應該使用單數名詞,因為: /book/123 看似比 /books/123 合理。但想想檔案系統的目錄命名 (例如/Users或/Docume"><meta name="keywords" content="Fullstack,REST"><meta property="og:type" content="article"><meta property="og:title" content="RESTful"><meta property="og:url" content="https://lruihao.cn/posts/restful.html"><meta property="og:site_name" content="菠菜眾長"><meta property="og:description" content="RESTful 是一種系統開發設計風格、原則。可視情況調整,以下參考來源 RFC5789 https://tools.ietf.org/html/rfc5789Noun一般資源通用於一律使用複數名詞例如:/books 或 /books/123。但有部分人認為應該使用單數名詞,因為: /book/123 看似比 /books/123 合理。但想想檔案系統的目錄命名 (例如/Users或/Docume"><meta property="og:locale" content="zh-CN"><meta property="og:updated_time" content="2019-11-14T11:17:21.338Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="RESTful"><meta name="twitter:description" content="RESTful 是一種系統開發設計風格、原則。可視情況調整,以下參考來源 RFC5789 https://tools.ietf.org/html/rfc5789Noun一般資源通用於一律使用複數名詞例如:/books 或 /books/123。但有部分人認為應該使用單數名詞,因為: /book/123 看似比 /books/123 合理。但想想檔案系統的目錄命名 (例如/Users或/Docume"><link rel="alternate" href="/atom.xml" title="菠菜眾長" type="application/atom+xml"><link rel="canonical" href="https://lruihao.cn/posts/restful.html"><script type="text/javascript" id="page.configurations">CONFIG.page={sidebar:""}</script><title>RESTful | 菠菜眾長</title><script type="text/javascript">var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?d25f1e053205bf07562f33365fef04d7";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><noscript><style type="text/css">.sidebar-inner,.use-motion .brand,.use-motion .collection-title,.use-motion .comments,.use-motion .menu-item,.use-motion .motion-element,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .logo,.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.logo-line-after i{right:initial}</style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">菠菜众长</span> <span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">李瑞豪的博客</h1></div><div class="site-nav-toggle"><button aria-label="切换导航栏"><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档<span class="badge">173</span></a></li><li class="menu-item menu-item-docs"><a href="/docs/" rel="section"><i class="menu-item-icon fa fa-fw fa-book"></i><br>综合</a></li><li class="menu-item menu-item-album"><a href="https://img.lruihao.cn" rel="external nofollow noopener noreferrer" target="_blank"><i class="menu-item-icon fa fa-fw fa-image"></i><br>相册</a></li><li class="menu-item menu-item-guestbook"><a href="/guestbook/" rel="section"><i class="menu-item-icon fa fa-fw fa-comments"></i><br>留言</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-address-card"></i><br>关于</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br>搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"><div style="text-align:center;padding:3px 0 0"><div style="margin-top:20px;font-size:18px;font-weight:600;border-bottom:1px solid #ccc"><i class="fa fa-history" aria-hidden="true"></i> 近期文章</div><ul style="margin:0;padding:0;list-style:none"><li><a href="/posts/year-2019.html" title="2019年度总结" target="_blank">2019年度总结</a></li><li><a href="/posts/sql.html" title="SQL总结" target="_blank">SQL总结</a></li><li><a href="/posts/cos-album.html" title="利用腾讯云为静态页面添加“动态”相册" target="_blank">利用腾讯云为静态页面添加“动态”相册</a></li><li><a href="/posts/restful.html" title="RESTful" target="_blank">RESTful</a></li><li><a href="/posts/phpPushUrl.html" title="php同时主动推送链接到百度,神马等站长平台" target="_blank">php同时主动推送链接到百度,神马等站长平台</a></li><li><a href="/posts/phpfile.html" title="php按行读取文件信息" target="_blank">php按行读取文件信息</a></li><li><a href="/posts/site-time.html" title="设置网站运行时间" target="_blank">设置网站运行时间</a></li><li><a href="/posts/async-defer.html" title="script的三种加载方式(async、defer)" target="_blank">script的三种加载方式(async、defer)</a></li><li><a href="/posts/Sublime-Text3.html" title="Sublime Text3快捷键大全" target="_blank">Sublime Text3快捷键大全</a></li><li><a href="/posts/netBeans.html" title="netBeans IDE开发设置" target="_blank">netBeans IDE开发设置</a></li><li><a href="/posts/dev-rules.html" title="web开发规则,代码规范" target="_blank">web开发规则,代码规范</a></li><li><a href="/posts/phpform.html" title="简单评论模块--php表单练习" target="_blank">简单评论模块--php表单练习</a></li><li><a href="/posts/phpfunc.html" title="php函数学习" target="_blank">php函数学习</a></li><li><a href="/posts/wamproot.html" title="WAMPServer自定义网站根目录等设置" target="_blank">WAMPServer自定义网站根目录等设置</a></li><li><a href="/posts/pysx2.html" title="python实训总结Ⅱ" target="_blank">python实训总结Ⅱ</a></li></ul></div></div></div></div></nav></div></header><a href="https://github.com/Lruihao/lruihao.github.io" class="github-corner" target="_blank" title="万水千山总是情,给个star行不行!" aria-label="万水千山总是情,给个star行不行!" rel="external nofollow noopener noreferrer"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#222;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><div class="reading-progress-bar"></div><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://lruihao.cn/posts/restful.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="李瑞豪"><meta itemprop="description" content="从ACM到Web,分享程序、技巧、干货,记录心情、学习、成长!"><meta itemprop="image" content="/images/avatar.png"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="菠菜眾長"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">RESTful<a href="https://github.com/Lruihao/lruihao.github.io/tree/hexo/source/_posts/restful.md" class="post-edit-link" title="编辑" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-pencil"></i></a></h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间:2019-11-14 19:06:05" itemprop="dateCreated datePublished" datetime="2019-11-14T19:06:05+08:00">2019-11-14</time> </span><span class="post-category"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-folder-o"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Fullstack/" itemprop="url" rel="index"><span itemprop="name">Fullstack</span></a></span> </span><span class="post-comments-count"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-comment-o"></i> </span><span class="post-meta-item-text">评论数: </span><a href="/posts/restful.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/posts/restful.html" itemprop="commentCount"></span> </a></span><span id="/posts/restful.html" class="leancloud_visitors" data-flag-title="RESTful"><span class="post-meta-divider">|</span> <span title="阅读次数"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="post-meta-item-text">阅读次数:</span> <span class="leancloud-visitors-count"></span></span></span><div class="post-symbolscount"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i> </span><span class="post-meta-item-text">本文字数:</span> <span title="本文字数">2,539</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-clock-o"></i> </span><span class="post-meta-item-text">阅读时长 ≈</span> <span title="阅读时长">4 分钟</span></div></div></header><div class="post-body" itemprop="articleBody"><blockquote><p>RESTful 是一種系統開發設計風格、原則。可視情況調整,以下參考來源 RFC5789 <a href="https://tools.ietf.org/html/rfc5789" rel="external nofollow noopener noreferrer" target="_blank">https://tools.ietf.org/html/rfc5789</a></p></blockquote><h2 id="Noun"><a href="#Noun" class="headerlink" title="Noun"></a>Noun</h2><ul><li>一般資源<br>通用於一律使用複數名詞<br>例如:/books 或 /books/123。但有部分人認為應該使用單數名詞,因為: /book/123 看似比 /books/123 合理。但想想檔案系統的目錄命名 (例如/Users或/Documents),其實用複數也沒問題。複數可以保持API endpoint的一致性,所以一般資源建議用複數。</li><li>唯一資源:對 client 而言只有一份的資源<br>通用於單數名詞<br>例如:user 是指目前驗證的使用者,使用者永遠只能同時登入一個使用者</li></ul><h2 id="Http-Method"><a href="#Http-Method" class="headerlink" title="Http Method"></a>Http Method</h2><table><tbody><tr><th>Method</th><th>Idempotent</th><th>Safe</th><th>CRUD</th><th>OO</th><th>生活動詞</th><th>用途</th></tr><tr><td rowspan="2">GET</td><td rowspan="2" style="text-align:center">Y</td><td rowspan="2" style="text-align:center">Y</td><td rowspan="2"><b>R</b>ead</td><td rowspan="2">get</td><td>get</td><td>取得資料</td></tr><tr><td>list</td><td>列出資料</td></tr><tr><td rowspan="2">POST</td><td rowspan="2"></td><td rowspan="2"></td><td rowspan="2"><b>C</b>reate</td><td rowspan="2">add</td><td>create</td><td>建立一個可以完全獨立存在的實體</td></tr><tr><td>add</td><td>增加一個必須依賴於某個實體的實體</td></tr><tr><td rowspan="2">PUT</td><td rowspan="2" style="text-align:center">Y</td><td rowspan="2"></td><td rowspan="3"><b>U</b>pdate</td><td rowspan="3">set</td><td>replace</td><td>取代一個關係,已存在時先刪除後建立,不存在時直接建立</td></tr><tr><td>add</td><td>附加唯一關係,兩個關係實體可以互相獨立存在,且已經存在</td></tr><tr><td>PATCH</td><td></td><td></td><td>edit</td><td>編輯某個實體</td></tr><tr><td>DELETE</td><td></td><td></td><td><b>D</b>elete</td><td>remove</td><td>remove<br>delete</td><td>刪除某個實體</td></tr></tbody></table><ul><li>Safe:該操作不會改變伺服器端的資源狀態 (而且結果可以被cache),屬於 Safe 的操作必定屬於 Idempotent</li><li>Idempotent (冪等性):該操作不管做1遍或做n遍,都會得到同樣的資源狀態結果 (但不一定得到同樣的回傳值,例如第2次DELETE請求可能回傳404),因此client端可以放心retry。</li></ul><h3 id="GET"><a href="#GET" class="headerlink" title="GET"></a>GET</h3><ul><li>SAFE:每次執行操作時,GET 只有讀取 Resource,不會改變到任何的 Resource (資源, 資料)</li><li>Idempotent:每次執行操作時,GET 只有讀取 Resource,不會改變到任何的 Resource (資源, 資料),所以任何資源的任何狀態都是一樣的</li></ul><h3 id="POST"><a href="#POST" class="headerlink" title="POST"></a>POST</h3><ul><li>每次執行操作時,POST 都會建立一個 Resource (資源, 資料)</li><li><p>範例:建立使用者<br>執行第一次時:建立一個 name = “帥小慶” 的 user,但其 id = 1執行第二次時:建立一個 name = “帥小慶” 的 user,但其 id = 2,發送同樣的請求,可每次都是不同的 Resource</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">POST /users</span><br><span class="line">Data:</span><br><span class="line"> {</span><br><span class="line"> "name": "帥小慶"</span><br><span class="line"> }</span><br></pre></td></tr></table></figure></li><li><p>Create:建立一個可以完全獨立存在的實體</p></li><li><p>範例:建立使用者<br>建立使用者前不需要建立任何的東西,就可以建立使用者了,使用者是可以完全獨立的存在</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">POST /users</span><br><span class="line">Data:</span><br><span class="line"> {</span><br><span class="line"> "name": "帥小慶"</span><br><span class="line"> }</span><br></pre></td></tr></table></figure></li><li><p>Add:增加一個必須依賴於某個實體的實體<br>資料結構:1對多的關係</p></li><li>範例:Add a public key on behalf of a user 增加一個代表使用者的公鑰 (Gitea API)<br>增加這個公鑰之前,使用者必須存在,公鑰必須歸屬於某個使用者之下公鑰跟姓名一樣,使用相同電腦的公鑰就會相同,但不表示是同一個使用者,故公鑰也會有自己的 ID我每次增加公鑰時,都將生成不同的公鑰 ID<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">POST /admin/users/{username}/keys</span><br></pre></td></tr></table></figure></li></ul><h3 id="PUT"><a href="#PUT" class="headerlink" title="PUT"></a>PUT</h3><ul><li>Idempotent:每次執行操作時,PUT 都會取代 Resource,不管操作幾次,使用者獲取得 Resource 結果都是一樣的</li><li>Replace:不論資源如何,最終的資源狀態都是一樣的<br>Resource 已存在時,或許不理會、或許先刪除後建立 (取代)Resource 不存在時,直接建立</li><li>Add:添加唯一關係,建立這個唯一關係前,兩個關連實體都必須存在。在沒有建立關係前,兩個關連實體都可以互相獨立存在</li><li>資料結構應為:多對多,且兩個關連實體的 PK,同時也是關係實體的 PK、FK</li><li><p>範例:增加使用者與角色的關係<br>增加使用者跟角色的關係前,使用者跟角色都必須存在;增加使用者跟角色的關係前,使用者跟角色可以獨立存在使用者 23240,跟角色 2,的關係最多只能有一條關係 (使用者 23240 有角色 2 ),最少沒有關係 (使用者 23240 沒有角色 2 )執行第二次操作時,使用者 23240 跟角色 2 的從屬關係仍然存在,也不會跑出第二條使用者 23240 跟角色 2 的從屬關係</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">PUT user/{account}/roles</span><br><span class="line">Data</span><br><span class="line"> {</span><br><span class="line"> "role_id": "2"</span><br><span class="line"> }</span><br></pre></td></tr></table></figure></li><li><p>範例:Follow a user 關注一個使用者 (Gitea)<br>增加關注關係時,關注者與被關注者 (都是使用者) 都必須存在;增加關注關係時,關注者與被關注者 (都是使用者) 都必須存在關注者使用者 23240,跟被關注者使用者 F3860056,的關係最多只能有一條關係 (23240 關注 F3860056),最少沒有關係 (23240 不關注 F3860056)執行第二次操作時,關注者 23240 跟被關注者 F3860056 的關注關係仍然存在,也不會跑出第二條關注者 23240 跟被關注者 F3860056 的關注關係</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">PUT /user/following/{username}</span><br></pre></td></tr></table></figure></li></ul><h3 id="PATCH"><a href="#PATCH" class="headerlink" title="PATCH"></a>PATCH</h3><ul><li>Edit:編輯可獨立存在、且已經存在的實體,也就是產生新版本的實體,可能會影響其他 Resource</li><li>範例:編輯使用者<br>編輯使用者,使用者已經存在,且我們可能有紀錄編輯時間、編輯人、編輯IP,所以每次的編輯都會造成不一樣的結果<br>第一次編輯使用者,更新時間變為 08:00,編輯人 23240,IP 10.151.110.165第二次編輯使用者,更新時間變為 09:00,編輯人 23241,IP 10.151.110.144<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">PATCH /users/{account}</span><br></pre></td></tr></table></figure></li></ul><h3 id="DELETE"><a href="#DELETE" class="headerlink" title="DELETE"></a>DELETE</h3><ul><li>Idempotent:每次執行操作時,DELETE 都會刪除相同的東西</li><li>範例:刪除使用者<br>第一次刪除使用者23240,刪除使用者23240第二次刪除使用者23240,還是刪除使用者23240,只不過使用者 23240 不存在了。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DELETE /users/{account}</span><br></pre></td></tr></table></figure></li></ul><h2 id="HTTP-Status-Code"><a href="#HTTP-Status-Code" class="headerlink" title="HTTP Status Code"></a>HTTP Status Code</h2><p>HTTP状态码(HTTP Status Code)是用以表示网页服务器HTTP响应状态的3位数字代码。所有状态码的第一个数字代表了响应的五种状态之一。 除非另有说明,状态码是HTTP / 1.1标准(RFC 7231)的一部分。</p><p>而关于 RESTful API 的请求状态,通常有以下两种设计方案:</p><ul><li>方案一:使用 HTTP 状态码来表示请求状态,200 时返回的内容就是数据;</li><li>方案二:所有接口都返回 200 ,在响应内容里约定 错误码 或 錯誤信息;</li></ul><p>在實際應用中,應據具體情景及需要進行選擇與調整。</p><table><tbody><tr><th>方案</th><th colspan="2">優劣比較</th></tr><tr><td rowspan="2">方案一</td><td>優點</td><td>對服務端來說較為簡單方便</td></tr><tr><td>缺點</td><td>客戶端難以根據狀態碼處理複雜問題</td></tr><tr><td rowspan="2">方案二</td><td>優點</td><td>方便對返回資料進行統一處理和細細微性的控制</td></tr><tr><td>缺點</td><td>相當於放棄了HTTP狀態碼的語義</td></tr></tbody></table><h3 id="常用HTTP狀態碼"><a href="#常用HTTP狀態碼" class="headerlink" title="常用HTTP狀態碼"></a>常用HTTP狀態碼</h3><table><tbody><tr><th>Code</th><th>Message</th><th>用途</th></tr><tr><th>1XX</th><th>Informational response</th><th>此類狀態碼通常代表的響應都是信息性的,告訴客戶端可以進行下一步操作。</th></tr><tr><td>100</td><td>Continue</td><td>表示服務端已接收到請求頭,客戶端可以繼續發送請求體(如POST請求)。</td></tr><tr><td>101</td><td>Switching Protocols</td><td>表示服務端支持更優協議,讓客戶端在服務端更換協議後重新訪問。</td></tr><tr><th>2XX</th><th>Successful</th><th>此類狀態碼通常代表請求已成功被服務端接收、理解并接受。</th></tr><tr><td>200</td><td>OK</td><td>表示請求成功。</td></tr><tr><td>201</td><td>Created</td><td>表示請求已被實現,通常是在成功創建了某個資源。</td></tr><tr><td>202</td><td>Accepted</td><td>表示請求已被服務端接收,但尚未進行處理。</td></tr><tr><td>204</td><td>No Content</td><td>表示請求成功,但不會返回任何內容。</td></tr><tr><td>205</td><td>Reset Content</td><td>表示請求成功,但不會返回任何內容,並且要求客戶端重置表單。</td></tr><tr><th>3XX</th><th>Redirect</th><th>此類狀態碼通常代表本次請求需要客戶端採取進一步操作才能完成。通常用於重定向。</th></tr><tr><td>300</td><td>Multiple Choices</td><td>表示請求的資源有多個供可選擇,客戶端可自行選擇一個進行請求的重定向。</td></tr><tr><td>301</td><td>Moved Permanently</td><td>表示請求的資源已經永久地移動到了新位置,並且將在Location域中攜帶該資源新的URI。</td></tr><tr><td>304</td><td>Not Modified</td><td>表示請求的資源無發生修改,將不會返回任何資源。</td></tr><tr><th>4XX</th><th>Client Error</th><th>此類狀態碼通常代表客戶端可能出現了錯誤。</th></tr><tr><td>400</td><td>Bad Request</td><td>表示客戶端發出的請求有誤(格式、大小、無效的…),服務端不能/不會處理該請求。</td></tr><tr><td>401</td><td>Unauthorized</td><td>表示客戶端未能提供必要的驗證,服務端拒絕提供資源。</td></tr><tr><td>403</td><td>Forbidden</td><td>表示服務端理解了該請求,但客戶端沒有足夠權限以訪問,遂拒絕提供該資源。</td></tr><tr><td>404</td><td>Not Found</td><td>表示服務端無法找到請求的資源,其可能已經暫時(永久)失效。</td></tr><tr><td>408</td><td>Request Timeout</td><td>表示請求超時。</td></tr><tr><td>409</td><td>Conflict</td><td>表示請求的資源發送了衝突,通常是PUT請求。</td></tr><tr><td>410</td><td>Gone</td><td>表示請求的資源已經永久失效,客戶端不應再次請求。</td></tr><tr><td>411</td><td>Length Required</td><td>表示服務端拒絕在沒有定義Content-Length頭的情況下接收該請求。</td></tr><tr><th>5XX</th><th>Server Error</th><th>此類狀態碼通常代表由於服務端的原因,導致無法完成請求。</th></tr><tr><td>500</td><td>Internal Server Error</td><td>表示由於服務端遇到意料之外的變故,導致無法完成請求。</td></tr><tr><td>501</td><td>Not Implemented</td><td>表示服務端不支持完成請求所需的功能,導致無法完成請求。</td></tr><tr><td>502</td><td>Bad Gateway</td><td>表示作為網関或代理的服務段在執行請求時,從上游服務器獲得了無效的響應。</td></tr><tr><td>503</td><td>Service Unavailable</td><td>表示由於某些原因(服務器超載或系統維護等),導致暫時無法完成請求。</td></tr><tr><td>504</td><td>Gatewy Timeout</td><td>表示作為網関或代理的服務段在執行請求時,未能及時從上游服務器獲得響應。</td></tr><tr><td>505</td><td>HTTP Version Not Supported</td><td>表示服務端不支持請求的HTTP協議版本,導致無法完成請求。</td></tr></tbody></table><blockquote><p>以上內容參考自<a href="https://zh.wikipedia.org/zh-tw/HTTP%E7%8A%B6%E6%80%81%E7%A0%81" rel="external nofollow noopener noreferrer" target="_blank">https://zh.wikipedia.org/zh-tw/HTTP%E7%8A%B6%E6%80%81%E7%A0%81</a>,<br>需要查看完整HTTP狀態碼請點擊<a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="external nofollow noopener noreferrer" target="_blank">https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html</a></p></blockquote></div><div class="popular-posts-header"><i class="fa fa-link"></i> 相关文章</div><!--[if !IE]><!--><details><summary style="cursor:pointer">点击查看</summary><!--<![endif]--><ul class="popular-posts"><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\webbiji.html" rel="bookmark">web汇总</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\links.html" rel="bookmark">各种Links汇总与分享</a></div></li></ul><!--[if IE]><!--></details><!--<![endif]--><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center"><div>欢迎关注公众号,感谢支持 !</div><button id="rewardButton" disable="enable" onclick="var qr = document.getElementById("QR"); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}"><span>赞赏</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/images/wechatpay.gif" alt="李瑞豪 微信支付"><p>微信支付</p></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/images/alipay.gif" alt="李瑞豪 支付宝"><p>支付宝</p></div></div></div></div><div class="copyright-box"><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者: </strong>李瑞豪</li><li><strong>修改时间: </strong>2019-11-14 19:17:21</li><li class="post-copyright-link"><strong>本文链接:</strong> <a href="https://lruihao.cn/posts/restful.html" title="RESTful">https://lruihao.cn/posts/restful.html</a></li><li class="post-copyright-license"><strong>版权声明: </strong>本博客所有文章除特别声明外,均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-creative-commons"></i> BY-NC-SA 4.0</a> 许可协议。转载请注明出处!</li></ul></div><div class="post-tags"><a href="/tags/Fullstack/" rel="tag"><i class="fa fa-tag"></i> Fullstack</a> <a href="/tags/REST/" rel="tag"><i class="fa fa-tag"></i> REST</a></div><footer class="post-footer"><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/posts/phpPushUrl.html" rel="next" title="php同时主动推送链接到百度,神马等站长平台"><i class="fa fa-chevron-left"></i> php同时主动推送链接到百度,神马等站长平台</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/posts/cos-album.html" rel="prev" title="利用腾讯云为静态页面添加“动态”相册">利用腾讯云为静态页面添加“动态”相册 <i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div id="sidebar-dimmer"></div><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap">站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="李瑞豪"><p class="site-author-name" itemprop="name">李瑞豪</p><p class="site-description motion-element" itemprop="description">从ACM到Web,分享程序、技巧、干货,记录心情、学习、成长!</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"><a href="/archives/"><span class="site-state-item-count">173</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"><a href="/docs/categories/index.html"><span class="site-state-item-count">25</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"><a href="/docs/tags/index.html"><span class="site-state-item-count">122</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/atom.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/Lruihao" title="GitHub → https://github.com/Lruihao" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-github"></i></a> </span><span class="links-of-author-item"><a href="https://blog.csdn.net/qq_39520417" title="CSDN → https://blog.csdn.net/qq_39520417" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-contao"></i></a> </span><span class="links-of-author-item"><a href="https://weibo.com/liahao" title="微博 → https://weibo.com/liahao" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-weibo"></i></a> </span><span class="links-of-author-item"><a href="/images/qq.jpg" title="QQ → /images/qq.jpg"><i class="fa fa-fw fa-qq"></i></a> </span><span class="links-of-author-item"><a href="mailto:1074627678@qq.com" title="E-Mail → mailto:1074627678@qq.com" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-envelope"></i></a></span></div><div class="cc-license motion-element" itemprop="license"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="external nofollow noopener noreferrer" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a></div><div class="links-of-blogroll motion-element links-of-blogroll-inline"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-globe"></i> 书签</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="/docs/donators/" title="/docs/donators/">赞助记录</a> </li><li class="links-of-blogroll-item"><a href="/docs/friends/" title="/docs/friends/">友情链接</a> </li><li class="links-of-blogroll-item"><a href="/posts/links.html" title="/posts/links.html">收藏夹</a> </li><li class="links-of-blogroll-item"><a href="/posts/font-mmt.html" title="/posts/font-mmt.html">MMT</a> </li><li class="links-of-blogroll-item"><a href="http://md.lruihao.cn" title="http://md.lruihao.cn" rel="external nofollow noopener noreferrer" target="_blank">WXMD</a> </li><li class="links-of-blogroll-item"><a href="/posts/webbiji.html" title="/posts/webbiji.html">WEB</a> </li></ul></div><iframe scrolling="no" src="https://tianqiapi.com/api.php?appid=72515596&appsecret=XDyzr75j&style=ta&skin=grape&align=center&fontsize=10&paddingtop=5&color=2f4f4f" frameborder="0" width="100%" height="20px" allowtransparency="true"></iframe></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Noun"><span class="nav-number">1.</span> <span class="nav-text">Noun</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Http-Method"><span class="nav-number">2.</span> <span class="nav-text">Http Method</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#GET"><span class="nav-number">2.1.</span> <span class="nav-text">GET</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#POST"><span class="nav-number">2.2.</span> <span class="nav-text">POST</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PUT"><span class="nav-number">2.3.</span> <span class="nav-text">PUT</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PATCH"><span class="nav-number">2.4.</span> <span class="nav-text">PATCH</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DELETE"><span class="nav-number">2.5.</span> <span class="nav-text">DELETE</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTTP-Status-Code"><span class="nav-number">3.</span> <span class="nav-text">HTTP Status Code</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#常用HTTP狀態碼"><span class="nav-number">3.1.</span> <span class="nav-text">常用HTTP狀態碼</span></a></li></ol></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">Copyright © 2018 – <span itemprop="copyrightYear">2020</span> <span class="with-love" id="animate"><i class="fa fa-heartbeat"></i> </span><span class="author" itemprop="copyrightHolder">LRH. </span> <span title="博客总字数"><i class="fa fa-edit"></i> <span class="post-count">114.4k</span>字</span></div><div class="busuanzi-count"><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="post-meta-item-icon"><i class="fa fa-user"></i> </span><span class="site-uv" title="总访客量"><span class="busuanzi-value" id="busuanzi_value_site_uv"><i class="fa fa-spinner fa-spin"></i></span> 人次 </span><span class="post-meta-divider">|</span> <span class="run-times" title="网站运行时间">载入天数时分秒...</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="site-pv" title="总访问量"><span class="busuanzi-value" id="busuanzi_value_site_pv"><i class="fa fa-spinner fa-spin"></i></span> 次</span></div><div class="weixin-box"><div class="weixin-menu"><div class="weixin-hover"><div class="weixin-description">微信扫一扫,订阅本博客</div></div></div></div><div class="beian" style="display:inline-block;height:20px;line-height:20px"><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=43030402000254" rel="external nofollow noopener noreferrer"><img src="/images/gov.png" style="float:left" alt="公安">湘公网安备43030402000254号</a> <span class="post-meta-divider" style="color:#555">|</span> <span><a href="http://www.beian.miit.gov.cn" target="_blank" rel="external nofollow noopener noreferrer">湘ICP备18020535号</a></span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js"></script><script type="text/javascript" src="/lib/reading_progress/reading_progress.js"></script><script type="text/javascript" src="/js/src/utils.js?v=6.7.0"></script><script type="text/javascript" src="/js/src/motion.js?v=6.7.0"></script><script type="text/javascript" src="/js/src/affix.js?v=6.7.0"></script><script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.7.0"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=6.7.0"></script><script type="text/javascript" src="/js/src/post-details.js?v=6.7.0"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=6.7.0"></script><script>$(".highlight").each(function(t,e){var n=$("<div>").addClass("highlight-wrap");$(e).after(n),n.append($("<button>").addClass("copy-btn").append("复制").on("click",function(t){var e=$(this).parent().find(".code").find(".line").map(function(t,e){return $(e).text()}).toArray().join("\n"),n=document.createElement("textarea");document.body.appendChild(n),n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.value=e,n.select(),n.focus();var o=document.execCommand("copy");document.body.removeChild(n),o?$(this).text("复制成功"):$(this).text("复制失败"),$(this).blur()})).on("mouseleave",function(t){var e=$(this).find(".copy-btn");setTimeout(function(){e.text("复制")},300)}).append(e)})</script><script>$("body").find("pre.mermaid").length&&$.ajax({type:"GET",url:"//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js",dataType:"script",cache:!0,success:function(){mermaid.initialize({theme:"forest",logLevel:3,flowchart:{curve:"linear"},gantt:{axisFormat:"%m/%d/%Y"},sequence:{actorMargin:50}})}})</script><script>function createTime(){var e=new Date,t=new Date("05/28/2018 20:01:01"),n=(e-t)/1e3,i=Math.floor(n/60/60/24),r=Math.floor(n/60/60-24*i),h=Math.floor(n/60-1440*i-60*r),a=Math.floor((e-t)/1e3-86400*i-3600*r-60*h);1===String(r).length&&(r="0"+r),1===String(h).length&&(h="0"+h),1===String(a).length&&(a="0"+a),document.querySelector(".run-times").innerHTML=i+" 天 "+r+" 时 "+h+" 分 "+a+" 秒"}if(document.hidden)clearInterval(siteTime);else var siteTime=setInterval("createTime()",500)</script><script type="text/javascript" src="/js/src/console.js"></script><script async type="text/javascript" src="/js/src/night.js"></script><div class="cover"></div><script async type="text/javascript" src="/js/src/crash-cheat.js"></script><script src="/js/src/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE)</script><script type="text/javascript" src="/js/src/love.js"></script><script type="text/javascript" src="/js/src/link-card.js" defer></script><script type="text/javascript" src="/js/src/pageQRcode.js" defer></script><script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><script>var GUEST=["nick","mail","link"],guest="nick,mail,link";guest=guest.split(",").filter(function(e){return-1<GUEST.indexOf(e)}),new Valine({el:"#comments",verify:!1,notify:!1,appId:"7HwTRT0Q0Tfrat6ugrT6P67c-gzGzoHsz",appKey:"mhTY1kuUmviCtQwkwOASfsfD",placeholder:"ヾノ≧∀≦)o~ 有事请留言!\n评论功能以邮件作为通知方式!\n如有必要请填写正确邮箱!",avatar:"wavatar",meta:guest,pageSize:"10",visitor:!0,lang:"zh-cn"})</script><script type="text/javascript">// Popup Window;
var isfetched = false;
var isXml = true;
// Search DB path;
var search_path = "search.xml";
if (search_path.length === 0) {
search_path = "search.xml";
} else if (/json$/i.test(search_path)) {
isXml = false;
}
var path = "/" + search_path;
// monitor main search box;
var onPopupClose = function (e) {
$('.popup').hide();
$('#local-search-input').val('');
$('.search-result-list').remove();
$('#no-result').remove();
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
}
function proceedsearch() {
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
.css('overflow', 'hidden');
$('.search-popup-overlay').click(onPopupClose);
$('.popup').toggle();
var $localSearchInput = $('#local-search-input');
$localSearchInput.attr("autocapitalize", "none");
$localSearchInput.attr("autocorrect", "off");
$localSearchInput.focus();
}
// search function;
var searchFunc = function(path, search_id, content_id) {
'use strict';
// start loading animation
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay">' +
'<div id="search-loading-icon">' +
'<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
'</div>' +
'</div>')
.css('overflow', 'hidden');
$("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');
$.ajax({
url: path,
dataType: isXml ? "xml" : "json",
async: true,
success: function(res) {
// get the contents from search data
isfetched = true;
$('.popup').detach().appendTo('.header-inner');
var datas = isXml ? $("entry", res).map(function() {
return {
title: $("title", this).text(),
content: $("content",this).text(),
url: $("url" , this).text()
};
}).get() : res;
var input = document.getElementById(search_id);
var resultContent = document.getElementById(content_id);
var inputEventFunction = function() {
var searchText = input.value.trim().toLowerCase();
var keywords = searchText.split(/[\s\-]+/);
if (keywords.length > 1) {
keywords.push(searchText);
}
var resultItems = [];
if (searchText.length > 0) {
// perform local searching
datas.forEach(function(data) {
var isMatch = false;
var hitCount = 0;
var searchTextCount = 0;
var title = data.title.trim();
var titleInLowerCase = title.toLowerCase();
var content = data.content.trim().replace(/<[^>]+>/g,"");
var contentInLowerCase = content.toLowerCase();
var articleUrl = decodeURIComponent(data.url);
var indexOfTitle = [];
var indexOfContent = [];
// only match articles with not empty titles
if(title != '') {
keywords.forEach(function(keyword) {
function getIndexByWord(word, text, caseSensitive) {
var wordLen = word.length;
if (wordLen === 0) {
return [];
}
var startPosition = 0, position = [], index = [];
if (!caseSensitive) {
text = text.toLowerCase();
word = word.toLowerCase();
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({position: position, word: word});
startPosition = position + wordLen;
}
return index;
}
indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
});
if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
isMatch = true;
hitCount = indexOfTitle.length + indexOfContent.length;
}
}
// show search results
if (isMatch) {
// sort index by position of keyword
[indexOfTitle, indexOfContent].forEach(function (index) {
index.sort(function (itemLeft, itemRight) {
if (itemRight.position !== itemLeft.position) {
return itemRight.position - itemLeft.position;
} else {
return itemLeft.word.length - itemRight.word.length;
}
});
});
// merge hits into slices
function mergeIntoSlice(text, start, end, index) {
var item = index[index.length - 1];
var position = item.position;
var word = item.word;
var hits = [];
var searchTextCountInSlice = 0;
while (position + word.length <= end && index.length != 0) {
if (word === searchText) {
searchTextCountInSlice++;
}
hits.push({position: position, length: word.length});
var wordEnd = position + word.length;
// move to next position of hit
index.pop();
while (index.length != 0) {
item = index[index.length - 1];
position = item.position;
word = item.word;
if (wordEnd > position) {
index.pop();
} else {
break;
}
}
}
searchTextCount += searchTextCountInSlice;
return {
hits: hits,
start: start,
end: end,
searchTextCount: searchTextCountInSlice
};
}
var slicesOfTitle = [];
if (indexOfTitle.length != 0) {
slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
}
var slicesOfContent = [];
while (indexOfContent.length != 0) {
var item = indexOfContent[indexOfContent.length - 1];
var position = item.position;
var word = item.word;
// cut out 100 characters
var start = position - 20;
var end = position + 80;
if(start < 0){
start = 0;
}
if (end < position + word.length) {
end = position + word.length;
}
if(end > content.length){
end = content.length;
}
slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
}
// sort slices in content by search text's count and hits' count
slicesOfContent.sort(function (sliceLeft, sliceRight) {
if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
return sliceRight.searchTextCount - sliceLeft.searchTextCount;
} else if (sliceLeft.hits.length !== sliceRight.hits.length) {
return sliceRight.hits.length - sliceLeft.hits.length;
} else {
return sliceLeft.start - sliceRight.start;
}
});
// select top N slices in content
var upperBound = parseInt('1');
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound);
}
// highlight title and content
function highlightKeyword(text, slice) {
var result = '';
var prevEnd = slice.start;
slice.hits.forEach(function (hit) {
result += text.substring(prevEnd, hit.position);
var end = hit.position + hit.length;
result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
prevEnd = end;
});
result += text.substring(prevEnd, slice.end);
return result;
}
var resultItem = '';
if (slicesOfTitle.length != 0) {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
} else {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
}
slicesOfContent.forEach(function (slice) {
resultItem += "<a href='" + articleUrl + "'>" +
"<p class=\"search-result\">" + highlightKeyword(content, slice) +
"...</p>" + "</a>";
});
resultItem += "</li>";
resultItems.push({
item: resultItem,
searchTextCount: searchTextCount,
hitCount: hitCount,
id: resultItems.length
});
}
})
};
if (keywords.length === 1 && keywords[0] === "") {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
} else if (resultItems.length === 0) {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
} else {
resultItems.sort(function (resultLeft, resultRight) {
if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
return resultRight.searchTextCount - resultLeft.searchTextCount;
} else if (resultLeft.hitCount !== resultRight.hitCount) {
return resultRight.hitCount - resultLeft.hitCount;
} else {
return resultRight.id - resultLeft.id;
}
});
var searchResultList = '<ul class=\"search-result-list\">';
resultItems.forEach(function (result) {
searchResultList += result.item;
})
searchResultList += "</ul>";
resultContent.innerHTML = searchResultList;
}
}
if ('auto' === 'auto') {
input.addEventListener('input', inputEventFunction);
} else {
$('.search-icon').click(inputEventFunction);
input.addEventListener('keypress', function (event) {
if (event.keyCode === 13) {
inputEventFunction();
}
});
}
// remove loading animation
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
proceedsearch();
}
});
}
// handle and trigger popup window;
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if (isfetched === false) {
searchFunc(path, 'local-search-input', 'local-search-result');
} else {
proceedsearch();
};
});
$('.popup-btn-close').click(onPopupClose);
$('.popup').click(function(e){
e.stopPropagation();
});
$(document).on('keyup', function (event) {
var shouldDismissSearchPopup = event.which === 27 &&
$('.search-popup').is(':visible');
if (shouldDismissSearchPopup) {
onPopupClose();
}
});</script><script>!function(){var t=document.createElement("script"),e=window.location.protocol.split(":")[0];t.src="https"===e?"https://zz.bdstatic.com/linksubmit/push.js":"http://push.zhanzhang.baidu.com/push.js";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}()</script><script src="/lib/pangu/dist/pangu.min.js?v=3.3"></script><script type="text/javascript">pangu.spacingPage()</script><script src="/lib/bookmark/bookmark.min.js?v=1.0"></script><script type="text/javascript">bookmark.scrollToMark("manual","#更多")</script><script>!function(e){var r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function t(){for(var c=0;c<r.length;c++)t=r[c],void 0,0<=(n=t.getBoundingClientRect()).top&&0<=n.left&&n.top<=(e.innerHeight||document.documentElement.clientHeight)&&function(){var t,n,e,i,o=r[c];t=o,n=function(){r=r.filter(function(t){return o!==t})},e=new Image,i=t.getAttribute("data-original"),e.onload=function(){t.src=i,n&&n()},e.src=i}();var t,n}t(),e.addEventListener("scroll",function(){!function(t,n){clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(n)},500)}(t,e)})}(this);</script></body></html>