【发布时间】: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