Tell us what’s happening:
Describe your issue in detail here.
project is handling post method with “url” and returns a short url but the test cases are not passing.
Code
const url = []
app.post("/api/shorturl", (req, res)=>{
dns.lookup(req.body.url.split("://")[1], (err, address)=>{
if(err){
return res.json({ error: 'invalid url' })
}
if(address){
let num = url.length
url[num]=req.body.url
return res.json({
original_url: url[num],
short_url: num
})
}
})
})
app.get("/api/shorturl/:num", (req,res)=>{
res.redirect(url[req.params.num])
})
Your project link(s)
solution: https://short-url-basic.herokuapp.com/url/shorturl
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0
Challenge: URL Shortener Microservice
Link to the challenge:
Above code is the only thing I’ve added to the index.js of boilerplate below. Rest is same.
Link : GitHub - freeCodeCamp/boilerplate-project-urlshortener: A boilerplate for a freeCodeCamp project.
All the Code in index.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { urlencoded } = require('body-parser');
const app = express();
const dns = require("dns")
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({extended: false}))
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' });
});
const url = []
app.post("/api/shorturl", (req, res)=>{
dns.lookup(req.body.url.split("://")[1], (err, address)=>{
if(err){
return res.json({ error: 'invalid url' })
}
if(address){
let num = url.length
url[num]=req.body.url
return res.json({
original_url: url[num],
short_url: num
})
}
})
})
app.get("/api/shorturl/:num", (req,res)=>{
res.redirect(url[req.params.num])
})
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});