【问题标题】:Express.js GET Route method Undefined?Express.js GET Route 方法未定义?
【发布时间】:2020-01-19 22:39:27
【问题描述】:

我遇到了这个问题。每当我在浏览器上发送 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 => { 如果(response.ok){ 返回响应.json(); } 别的 { 渲染错误(响应); } }) .then(响应 => { renderQuotes([response.quote]); }); });

请帮帮我!感谢您的所有帮助。

【问题讨论】:

  • 你能添加你的 api 的整个 res 对象吗?
  • 在你的路由之后使用 app.use('/api/quotes', quotesRouter)

标签: javascript node.js express


【解决方案1】:

这里可能需要对您的快速代码进行调整。但是,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}) })

【讨论】:

  • 感谢您的帮助!我会在上面的前端给你我的代码
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
相关资源
最近更新 更多