Hello. I am working on the URL Shortener project on Replit. I was able to get the first two requirements from freeCodeCamp.
- Provide your own project, Replit.
- If you pass an invalid URL that doesn’t follow the valid
http://www.example.com
format, the JSON response will contain { error: 'invalid url' }
But now I am struggling with these other two test requirements.
-
You can POST a URL to /api/shorturl
and get a JSON response with original_url
and short_url
properties. Here’s an example: { original_url : 'https://freeCodeCamp.org', short_url : 1}
-
When you visit /api/shorturl/<short_url>
, you will be redirected to the original URL.
This is the original server.js code structure for URL Shortener in Replit
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
// Your first API endpoint
app.get('/api/hello', function(req, res) {
res.json({ greeting: 'hello API' });
});
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});
This is what I coded in server.js file
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
// Basic Configuration ********
const port = process.env.PORT || 3000;
//=== I tried to include my MONGO_URI code
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true} );
console.log(mongoose.connect.readyState)
// const mySecret = process.env['MONGO_URI']
//=== ^ Is this how I should put the mongo code in here?
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
//=== Your first API endpoint. This is where I know I should code here.
app.post('/api/shorturl', function(req, res) {
console.log(req.body);
const bodyurl = req.body.url;
const something = dns.lookup(urlparser.parse(bodyurl).hostname, (error, address) => {
if(!address) {
res.json({error: "Invalid URL"})
} else {
const url = new Url({ url: bodyurl })
url.save((error, data) => {
res.json({
original_url: data.url,
short_url: data.id
})
})
}
console.log("dns", error);
console.log("address", address);
})
console.log("something", something);
});
app.get("/api/shorturl/:id", (req, res) => {
const id = req.params.id;
Url.findById(id, (error, data) => {
if(!data){
res.json({error: "Invalid URL"})
} else {
res.redirect(data.url)
}
})
})
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});
Please let me know where I made my error, what I am missing and how I should fix it.
Thank you