I ran into this problem. whenever I send a GET request on the browser. I received this message get undefined when using fetch on the browser
.
I do not know why and this is my code.
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});
})
updated
fetchRandomButton.addEventListener('click', () => {
fetch('/api/quotes/random').then(response => { if (response.ok) { return response.json(); } else { renderError(response); } }).then(response => { renderQuotes([response.quote]); }); });
please helping me out. I appreciate all your help.
Here's a tweak to your express code that might be needed. However, fetch is typically a front end javascript thing so are you sure it's being used correctly on the front end?
Check here in the fetch docs to verify you're calling fetch correctly.
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}) })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.