[英]Express API confusion - what exact part of my express app is the API?
問這個問題我覺得有點愚蠢,但我正在 Codecademy 練習中構建一個快速的 API 應用程序,我實際上並不了解應用程序的哪一部分是 API。
基本上,您有一個包含一堆引號的文件,這些引號顯示給瀏覽器。 通過瀏覽器,您可以提取隨機報價(點擊“隨機報價按鈕”)、提取所有報價或添加您自己的報價。
那么API到底在哪里呢? 我知道 API 是兩個軟件之間的接口,但我不明白它在這種情況下是如何工作的。 無論如何,作為一個例子,這里是“獲取所有引號”功能的代碼:
腳本.js
fetchAllButton.addEventListener('click', () => {
fetch('/api/quotes')
.then(response => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then(response => {
renderQuotes(response.quotes);
});
});
服務器.js
app.get('/api/quotes', (req, res) => {
let quoteMatch;
let quoteSearch = req.query.person;
if (quoteSearch == undefined) {
res.send({quotes: quotes})
} else {
quotesMatch = quotes.filter(quote => {
return quote.person == quoteSearch && quote;
});
if (quoteMatch) {
res.send({ quotes: quotesMatch });
} else {
res.status(404).send('Author not found!! 😡');
}
}
})
數據.js
const quotes = [
{
quote: 'We build our computer (systems) the way we build our cities: over time, without a plan, on top of ruins.',
person: 'Ellen Ullman'
},
{
quote: 'The best thing about a boolean is even if you are wrong, you are only off by a bit.',
person: 'Anonymous'
},
server.js
文件中的 API 代碼。
scripts.js
:從前端調用 API。
您的 script.js 是您向 /api/quotes 發出請求的客戶端,而您的 server.js 是正在處理請求的 API
app.get('/api/quotes', (req, res) => {
})
server.js 文件中的這段代碼在 API 中稱為 route
你的 API 是 server.js 監聽 url: '/api/quotes' 然后響應 res.send({quotes: quotes} by html get 方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.