Tell us what’s happening:
I cannot pass the URL Shortener Microservice. I tried my project and it can response with JSON with original_url
and short_url
properties & redirect it to the original URL as required. So I’m not sure why I cannot pass it… hope others’ insight could help ><
Is it necessary to use Mongoose? I didn’t use mongoose in the project though…
Thank you for any help :’(
Your code so far
project link: https://boilerplate-project-urlshortener.snowiewdev.repl.co/
code link: https://repl.it/join/icuivlbo-snowiewdev
serverjs:
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const dns = require('dns');
const bodyParser = require('body-parser');
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
const links = [];
let id = 0;
// Your first API endpoint
app.post('/api/shorturl/new', function(req, res) {
const { url } = req.body;
const noHTTPSurl = url.replace(/^https?:\/\//, '');
dns.lookup(noHTTPSurl, (err) => {
if(err) {
return res.json({
"error": "invalid URL"
});
} else {
id++;
const link = {
original_url: url,
short_url: `${id}`
};
links.push(link);
console.log(link);
return res.json(link);
}
});
});
app.get('/api/shorturl/:id', (req, res) => {
const { id } = req.params;
const link = links.find(a => a.short_url === id);
if(link) {
return res.redirect(link.original_url);
} else {
return res.json({
error: 'No short url'
});
}
})
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36
.
Challenge: URL Shortener Microservice
Link to the challenge: