Hello campers.
I have an issue with this project. Although my project works as it should i can’t pass test 2 and test 3. I return json like this {"original_url":"https://freeCodeCamp.org","short_url":"JSytVEpZL"}
on the link /api/shorturl
. And redirect on the site if i go /api/shorturl/JSytVEpZL
. I have all instances in my MongoDB Cluster
Link to my project https://replit.com/@RomanMarchuk1/boilerplate-project-urlshortener-2#server.js
Here is server.js
require('dotenv').config();
const express = require('express');
const shortId = require("shortid")
const validUrl = require("valid-url")
const cors = require('cors');
const dns = require("dns")
const app = express();
const mongoose = require("mongoose")
const mySecret = process.env['newMONGO_URI']
mongoose.connect(mySecret, { useNewUrlParser: true, useUnifiedTopology: true })
console.log("mongoose connection state:" + mongoose.connection.readyState)
const Schema = mongoose.Schema
const mySchema = new Schema({
urlCode:{type:String, required:true},
url:{type:String, required:true},
})
let MyUrl1 = mongoose.model("MyUrl1", mySchema)
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.use(express.urlencoded({ extended: true }))
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
// Your first API endpoint
app.post("/api/shorturl", (req, res)=>{
let urlId = shortId.generate()
const hostname = req.body.url.replace(/https?:\/\//, "");
dns.lookup(hostname, (err, adr, fam)=>{
if(err){
res.json({ error: 'invalid url' })
}
else{
try{res.json({original_url:req.body.url, short_url:urlId})
let newUrl = new MyUrl1({
urlCode:urlId,
url:req.body.url
})
newUrl.save()} catch(err){
console.error(err)
}
}
})
})
app.get("/api/shorturl/:shortUrl", async (req, res)=>{
try{
const urlParam = await MyUrl1.findOne({urlCode:req.params.shortUrl})
if (urlParam){
return res.redirect(urlParam.url)
}
else{
return res.status(404).json("No URL Found")
}
}catch(err){
console.log(err)
res.status(500).json("Server Error")
}
})
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/90.0.4430.93 Safari/537.36
.
Challenge: URL Shortener Microservice
Link to the challenge: