Tell us what’s happening:
Describe your issue in detail here.
I have finished the challenge shortened url and have tested it manually. It is yielding the result as expected but somehow the automated test of freecodecamp does not succeed
My code
require(‘dotenv’).config();
const bodyParser = require(‘body-parser’);
const mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const express = require(‘express’);
const cors = require(‘cors’);
const app = express();
const crypto = require(‘crypto’);
const dns = require(‘dns’);
//Use body-parser to Parse POST Requests
app.use(bodyParser.urlencoded({ extended: false }));
// Define regular expression for URL format
const urlRegex = /^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(/.)?$/i;
const shortUrlSchema = new mongoose.Schema({
original_url: { type: String, required: true },
short_url: String
});
const ShortUrl = mongoose.model(“ShortUrl”, shortUrlSchema);
// 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’ });
});
// Create a short url in the database
app.post(‘/api/shorturl’, async (req, res) => {
const { url } = req.body;
if (!urlRegex.test(url)) {
res.status(400).json({error: ‘invalid url’});
return;
}
// Generate hash of URL
const hash = crypto.createHash(‘sha256’).update(url).digest(‘hex’);
// Check if URL already exists in database
const existingUrl = await ShortUrl.findOne({ original_url: url });
if (existingUrl) {
console.log(“url already exists”)
res.json({ original_url: url, short_url: existingUrl.short_url });
} else {
// Create new URL record
const newUrl = new ShortUrl({
original_url: url,
short_url: hash.slice(0, 8) // Use first 8 characters of hash as shortened URL
});
// Save new URL record to database
await newUrl.save();
res.json({ original_url: url, short_url: newUrl.short_url });
}
});
// Redirect to the original Url
app.get(‘/api/shorturl/:url’, async (req, res) => {
const shorturl = req.params.url;
// Look up original URL in database
const url = await ShortUrl.findOne({ short_url: shorturl });
if (url) {
res.redirect(url.original_url);
} else {
res.status(404).send(‘URL not found’);
}
});
app.listen(port, function() {
console.log(Listening on port ${port}
);
});
Your project link(s)
solution: https://boilerplate-project-urlshortener--phuc41002487.repl.co
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0
Challenge Information:
Back End Development and APIs Projects - URL Shortener Microservice