Tuesday, 16 June 2020

GET request not working on Postman

I'm working on a url-shortener project. I've managed to implement the POST request that stores the url and the short url in the database. However, I've been stuck trying to make a GET request to retrieve the shortened url. It displays the error 'Cannot GET /api/url'. I have tried with with different queries to the database but still no success. Can someone please take a look at my code and help me with what's wrong?index.jsconst express = require('express');const connectDB = require('./config/db');const app = express();connectDB();app.use(express.json({ extended: false}));//Define Routes// app.use('/', require('./routes/index'));app.use('/api/url', require('./routes/url'));const PORT = process.env.PORT || 5000;app.listen(PORT, () => console.log(\Server running on port ${PORT}`));`​routes/url.jsconst express = require('express');const router = express.Router();const validUrl = require('valid-url');const shortid = require('shortid');const config = require('config');const Url = require('../models/Url');//@route GET /api/url/:code//@desc Get shortened link by idrouter.get('/:id', async(req, res) => {try {const url = await Url.findById(req.params.id);if(url) {return res.redirect(url.longUrl);        } else {return res.status(404).json('No url found');        }    } catch(err) {console.error(err);res.status(500).json('server error');    }});module.exports = router;

Submitted June 16, 2020 at 01:48PM by bhaelar

No comments:

Post a Comment