Hi I am getting an error and it is stumping me. I think its on line 33 in “server.js.” Here is all the things that were contributed in the coding.
Server.js
require('dotenv').config();
const express = require('express');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');
const dns = require('dns');
const urlparser = require('url');
const app = express();
// Basic Configuration
const port = process.env.PORT || 3000;
mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(mongoose.connection.readyState)
const schema = new mongoose.Schema({url: 'string'});
const Url = mongoose.model('Url', schema);
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.post('/api/shorturl/new', 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((err, 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, (err, data) => {
if(!data){
res.json({error: "Invalid URL"})
}else{
res.redirect(data.url)
}
})
})
app.listen(port, function() {
console.log('Listening on port ${port}');
});
.env
PORT=5000
DB_URI="mongodb+srv://user1:<pass>@cluster0.3gehg.mongodb.net/urlshortener?retryWrites=true&w=majority"
package.json
{
"name": "shorturl",
"version": "0.0.3",
"description": "API project for freeCodeCamp",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.10.15",
"mongodb": "^3.6.0"
},
"engines": {
"node": "12.18.3"
},
"license": "MIT",
"devDependencies": {
"nodemon": "^2.0.4"
}
}
Tell us what’s happening:
Your code so far
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.72 Safari/537.36
.
Challenge: URL Shortener Microservice
Link to the challenge: