MongoDB + Node를 사용하여 URL Shortener 프로젝트를 생성하세요.

간단한 URL 단축기 프로젝트를 구축하여 MongoDB, Mongoose, Node 및 기타 기술에 대해 알아봅시다.

빠른 URL 단축기를 직접 만들 수 있는 방법에 대해 궁금한 적이 있습니까? 링크를 공유할 때 Twitter에서 링크를 줄이는 방법처럼요? 또는 bit.ly는 어떻게 작동합니까?

물론 이들은 복잡한 회사이지만 URL 단축기의 개념은 간단합니다. 7단계로 이 프로젝트를 실제로 빌드하면서 MongoDB 및 기타 백엔드 도구에 대해 알아봅시다.

프로젝트 소개



우리는 codedamn에서 이free URL shortener classroom를 사용하여 실습 프로젝트를 실제로 만들고 평가하고 피드백을 볼 것입니다.

우리는 다음 기술을 사용할 것입니다.
  • 몽구스를 ORM으로 사용
  • 백엔드 데이터베이스로서의 MongoDB
  • Node.js를 백엔드로 사용
  • 프런트엔드로 간단한 내장 JS 파일

  • 랩 1: Express 서버 설정





    링크는 이쪽lab is here

    상당히 간단한 실험실입니다. 적절하게 응답해야 하는 경로/short를 생성하기만 하면 됩니다. 이 코드를 사용하면 다음을 통과할 수 있습니다.

    // Initialize express server on PORT 1337
    const express = require('express')
    const app = express()
    
    app.get('/', (req, res) => {
        res.send('Hello World! - from codedamn')
    })
    
    app.get('/short', (req, res) => {
        res.send('Hello from short')
    })
    
    app.listen(process.env.PUBLIC_PORT, () => {
        console.log('Server started')
    })
    

    랩 2: 보기 엔진 설정





    링크는 이쪽lab is here

    단일.ejs 파일을 사용하고 있으므로 조금 살펴보겠습니다. 다시 말하지만 변수의 이름만 변경하면 되기 때문에 매우 간단한 실습입니다. 이렇게 하면 작업이 완료됩니다.

    const express = require('express')
    const app = express()
    
    app.set('view engine', 'ejs')
    
    app.get('/', (req, res) => {
        res.render('index', { myVariable: 'My name is John!' })
    })
    
    app.listen(process.env.PUBLIC_PORT, () => {
        console.log('Server started')
    })
    

    실습 3: MongoDB 설정





    이쪽의 링크lab is here

    이 실습에서는 MongoDB에 올바르게 연결하고 레코드에 대해서만 레코드를 삽입합니다.

    이것이 우리를 다음 실습으로 이끄는 솔루션입니다.

    app.post('/short', (req, res) => {
        const db = mongoose.connection.db
        // insert the record in 'test' collection
        db.collection('test').insertOne({ testCompleted: 1 })
    
        res.json({ ok: 1 })
    })
    
    // Setup your mongodb connection here
    mongoose.connect('mongodb://localhost/codedamn', {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    mongoose.connection.on('open', () => {
        // Wait for mongodb connection before server starts
        app.listen(process.env.PUBLIC_PORT, () => {
            console.log('Server started')
        })
    })
    

    랩 4: Mongoose 스키마 설정





    링크는 이쪽lab is here

    마지막으로 Mongoose를 적절하게 처리하기 위해 models/url.js 파일에 스키마를 정의하고 여기에 해당 코드가 있습니다.

    const mongoose = require('mongoose')
    const shortId = require('shortid')
    
    const shortUrlSchema = new mongoose.Schema({
      full: {
        type: String,
        required: true
      },
      short: {
        type: String,
        required: true,
        default: shortId.generate
      },
      clicks: {
        type: Number,
        required: true,
        default: 0
      }
    })
    
    module.exports = mongoose.model('ShortUrl', shortUrlSchema)
    

    또한 도전의 일환으로 지금 /short 경로를 업데이트합니다.

    app.post('/short', async (req, res) => {
        // insert the record using the model
        const record = new ShortURL({
            full: 'test'
        })
        await record.save()
        res.json({ ok: 1 })
    })
    

    실습 5: 프런트엔드, 백엔드, + MongoDB 연결





    이것은 또한 간단한 실험실입니다. 전달된 URL을 추출하고 스키마를 사용하여 데이터베이스에 저장하기 위해 경로를 업데이트하기만 하면 됩니다.

    app.use(express.urlencoded({ extended: false }))
    
    app.post('/short', async (req, res) => {
        // Grab the fullUrl parameter from the req.body
        const fullUrl = req.body.fullUrl
        console.log('URL requested: ', fullUrl)
    
        // insert and wait for the record to be inserted using the model
        const record = new ShortURL({
            full: fullUrl
        })
    
        await record.save()
    
        res.redirect('/')
    })
    

    실습 6: 프런트엔드에 단축 URL 표시





    이제 전달된 .ejs 변수를 사용하여 웹 사이트에 설정된 URL을 표시합니다.

    app.get('/', async (req, res) => {
        const allData = await ShortURL.find()
        res.render('index', { shortUrls: allData })
    })
    

    실습 7: 리디렉션 작동시키기





    마지막으로 동적 익스프레스 경로와 올바른 상태 코드를 사용하여 리디렉션 체계를 연결합니다.

    app.get('/:shortid', async (req, res) => {
        // grab the :shortid param
        const shortid = req.params.shortid
    
        // perform the mongoose call to find the long URL
        const rec = await ShortURL.findOne({ short: shortid })
    
        // if null, set status to 404 (res.sendStatus(404))
        if (!rec) return res.sendStatus(404)
    
        // if not null, increment the click count in database
        rec.clicks++
        await rec.save()
    
        // redirect the user to original link
        res.redirect(rec.full)
    })
    

    결론



    그리고 우리는 그것을 하루라고 부를 수 있습니다! Express + Node + MongoDB를 사용하여 완전히 작동하는 URL 단축기를 직접 구축했습니다. 자신에게 등을 두드려주세요!

    최종 소스 코드는 GitHub에서 사용할 수 있습니다.

    이 기사나 코드젠더 강의실에 대한 피드백이 있으면 언제든지 Twitter에서 저에게 연락해 주세요. 상의하자 :)

    좋은 웹페이지 즐겨찾기