簡體   English   中英

Express.js GET Route 方法未定義?

[英]Express.js GET Route method Undefined?

我遇到了這個問題。 每當我在瀏覽器上發送 GET 請求時。 get undefined when using fetch on the browser

在瀏覽器上使用 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();

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM