I’m a beginner in nodejs and I’m having trouble passing the tests about the tests about redirecting to the original url and returning the json response even though I have tested multiple times that these functions work. The link to my project is boilerplate-project-urlshortener - Replit and my code so far is as follows:
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const mongoose = require("mongoose")
const Url = require('./url')
const baseURL = "http://localhost:3000"
const dns = require('node:dns');
const MongoClient = require('mongodb').MongoClient;
const mongo_username = process.env['MONGO_USERNAME']
const mongo_password = process.env['MONGO_PASSWORD']
// const uri = `mongodb://<${mongo_username}>:<${mongo_password}>@main-shard-00-00-03xkr.mongodb.net:27017,main-shard-00-01-03xkr.mongodb.net:27017,main-shard-00-02-03xkr.mongodb.net:27017/main?ssl=true&replicaSet=Main-shard-0&authSource=admin&retryWrites=true`;
const uri = `mongodb://${mongo_username}:${mongo_password}@ac-lj86b4m-shard-00-00.echj7n9.mongodb.net:27017,ac-lj86b4m-shard-00-01.echj7n9.mongodb.net:27017,ac-lj86b4m-shard-00-02.echj7n9.mongodb.net:27017/?ssl=true&replicaSet=atlas-8jml05-shard-0&authSource=admin&retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true });
mongoose.set('strictQuery', false)
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use(express.urlencoded({ extended: true }))
const shortid = require('shortid');
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.get('/api/shorturl/:id', async function(req, res) {
client.connect(async (err) => {
if (err) console.log(err)
const url = client.db("urlShortener").collection('Urls')
const existingUrl = await url.findOne({ shortURL: req.params.id }) || null
if (existingUrl) {
console.log(existingUrl.longUrl)
return res.redirect(existingUrl.longUrl)
}
else res.json({ message: "non existing url" })
})
})
app.post('/api/shorturl', async (req, res) => {
const isValidUrl = (urlString) => {
let url;
try {
url = new URL(urlString);
}
catch (e) {
return false;
}
return url.protocol === "http:"
}
const urlInput = req.body.url
if (!isValidUrl(urlInput)) return res.json({ error: 'invalid url' })
else {
client.connect(async (err) => {
if (err) console.log(err)
const url = client.db("urlShortener").collection('Urls')
const existing = await url.findOne({ longUrl: urlInput })
if (existing) return res.json({
original_url: existing.longUrl,
short_url: existing.shortURL
})
const id = shortid.generate()
const newUrl = await url.insertOne({
longUrl: urlInput,
shortURL: id
})
return res.json({ original_url: urlInput, short_url: id })
})
}
})
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/108.0.0.0 Safari/537.36
Challenge: Back End Development and APIs Projects - URL Shortener Microservice
Link to the challenge: