[英]Express.js GET Route method Undefined?
我遇到了這個問題。 每當我在瀏覽器上發送 GET 請求時。 get undefined when using fetch on the browser
。
我不知道為什么,這是我的代碼。
const express = require(‘express’);
const app = express();
const { quotes } = require(’./data’);
const { getRandomElement } = require(’./utils’);
const PORT = process.env.PORT || 3004;
app.use(express.static(‘public’));
const quotesRouter = express.Router();
app.use(’/api/quotes’, quotesRouter);
quotesRouter.get(’/random’,(req, res, next)=> {
let randomQuote = (quotes);
if (randomQuote) res.send(randomQuote);
else res.status(404).send();
});
app.listen(PORT, () => {
console.log(Server listening on ${PORT});
})
更新
fetchRandomButton.addEventListener('click', () => {
fetch('/api/quotes/random').then(response => { if (response.ok) { return response.json(); } else { renderError(response); } }).then(response => { renderQuotes([response.quote]); }); });
請幫幫我。 我感謝您的所有幫助。
這是您可能需要的快速代碼的調整。 但是,fetch 通常是前端 javascript 的東西,所以你確定它在前端被正確使用了嗎?
在 fetch 文檔中查看此處以驗證您是否正確調用了 fetch。
const express = require(‘express’);
const app = express();
const { quotes } = require(’./data’);
const { getRandomElement } = require(’./utils’);
const PORT = process.env.PORT || 3004;
app.use(express.static(‘public’));
const quotesRouter = express.Router();
quotesRouter.get(’/random’, (req,res,next)=> {
let randomQuote=getRandomElement(quotes);
if (randomQuote) {
res.send(randomQuote);
} else {
res.status(404).send();
}
});
app.use(’/api/quotes’, quotesRouter); <-- moved this to here
app.listen(PORT, ()=>{ console.log(Server listening on ${PORT}) })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.