index.js (url shortener)
unknown
javascript
2 years ago
2.7 kB
3
Indexable
require('dotenv').config(); const express = require('express'); const cors = require('cors'); const app = express(); const dns = require('dns') const bodyParser = require('body-parser') const mongoose = require("mongoose") //var router = express.Router(); // Basic Configuration const port = process.env.PORT || 3000; mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }); //throw error if connection isnt met const db = mongoose.connection; db.on("error", console.error.bind(console, "connection error: ")) db.once("open", () =>{ console.log("Connected successfully") }) app.use(cors()); app.use('/public', express.static(`${process.cwd()}/public`)); const urlSchema = new mongoose.Schema({ longUrl: { type: String, required: true, }, shortUrl : { type: String } }) const url = mongoose.model('url', urlSchema) //generate alphanumeric value of four characters, check if this value exists in the database const randomStr= () => { let val = Math.random().toString(16).slice(2,6) if (url.exists({shortUrl: val}) == null) { return val } else{ randomStr() } } //create a shortened url from a link const createUrl = (str) => { //check if url is valid dns.lookup(str, (error, address, family) =>{ if (error){ console.log(error) return res.json({ error: 'invalid url' }) } }) //check if original url does not exist in database if(url.exists({longUrl: str} === null)){ url.create({longUrl: str, shortUrl: randomStr()}) //verify process return True } else{ return False } } //post request adding a url to the database app.post("/api/shorturl", bodyParser.urlencoded({extended: false}), (req, res) => { if (createUrl(req.body) === true){ createUrl(req.body) smallUrl = url.find({ longUrl: req.body}, 'shortUrl') res.json({longUrl: req.body, shortUrl: smallUrl }) } }) 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/:shorturl', (req,res) => { let link = req.params.shorturl }) app.listen(port, function() { console.log(`Listening on port ${port}`); }); Console: TypeError [ERR_INVALID_ARG_TYPE]: The "hostname" argument must be of type string. Received [Object: null prototype] at new NodeError (node:internal/errors:372:5) at validateString (node:internal/validators:120:11) at Object.lookup (node:dns:105:5) at createUrl (/home/runner/boilerplate-project-urlshortener/index.js:54:9)
Editor is loading...