Tuesday, October 31, 2023

Nitheen Kumar

JavaScript jQuery for route URL Node.js from database

 To route URLs from a database in JavaScript, you typically need a server-side language (like Node.js) to interact with the database and manage routing. Here's a simplified example of how you might approach this using Node.js and Express.js as your server framework:


Assuming you have a database containing URL mappings, let's say a "routes" table with columns "short_url" and "full_url," you can use JavaScript to create an API that fetches the full URL based on the provided short URL.


First, make sure you have Node.js and Express.js installed.


Set up your project:


bash code

npm init

npm install express mysql

Create your JavaScript file (e.g., server.js):

javascript code

const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000; // Replace with your desired port


// Create a MySQL database connection

const db = mysql.createConnection({

  host: 'localhost',

  user: 'your_user',

  password: 'your_password',

  database: 'your_database',

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to database:', err);

    return;

  }

  console.log('Connected to database');

});


// Define a route to handle short URL redirection

app.get('/:shortUrl', (req, res) => {

  const shortUrl = req.params.shortUrl;


  // Fetch the corresponding full URL from the database

  const query = 'SELECT full_url FROM routes WHERE short_url = ?';

  db.query(query, [shortUrl], (error, results) => {

    if (error) {

      console.error('Error retrieving URL:', error);

      res.status(500).send('Error retrieving URL');

    } else if (results.length > 0) {

      const fullUrl = results[0].full_url;

      res.redirect(fullUrl);

    } else {

      res.status(404).send('URL not found');

    }

  });

});


app.listen(port, () => {

  console.log(`Server is running on port ${port}`);

});

Make sure you replace the database connection details with your own. This code sets up a basic Express server and MySQL database connection. It listens for requests with a short URL parameter and looks up the corresponding full URL in the database.


Start the server:


bash code

node server.js

Now, when you visit http://localhost:3000/your_short_url, it will redirect you to the full URL stored in the database for that short URL. Make sure your database schema matches the example provided, and you have populated it with appropriate data.

Subscribe to get more Posts :