Connecting Oracle Database with Node.js

Prerequisites: Before we begin, make sure you have the following prerequisites:

1.Node.js installed on your machine.

2.Access to an Oracle Database instance.

3.The 'oracledb', 'express', and 'cors' modules installed for Node.js.

Step 1: Installing the Required Modules

To establish a connection between Node.js and Oracle Database, as well as enable CORS, we need to install the necessary modules. Open your terminal or command prompt and execute the following command:

npm install oracledb express cors

Step 2: Establishing the Connection and Setting Up CORS

To begin, create a new JavaScript file (e.g., app.js) and require the necessary modules at the beginning:

const express = require('express');

const oracledb = require('oracledb');

const cors = require('cors');

app.use(cors());

const app = express();

const port = 3000;

Next, configure the CORS middleware to allow cross-origin requests. Add the following code snippet:

app.use(cors());

Step 3: Establishing the Database Connection

To connect to the Oracle Database, define the database connection configuration, including the hostname, port number, service name, and credentials:

const dbConfig = {

user: 'your_username',

password: 'your_password',

connectString: 'your_connection_string'

};

Replace 'your_username', 'your_password', and 'your_connection_string' with your actual Oracle Database credentials and connection string.

Now, let's establish the connection:

oracledb.getConnection(dbConfig, (err, connection) => {

if (err) {

console.error(err.message);

return;

}

console.log('Connected to Oracle Database!');

// Database operations will be performed here

// Closing the connection

app.on('close', () => {

connection.close((err) => {

if (err) {

console.error(err.message);

return;

}

console.log('Connection closed.'); });

});

});

Step 4: Executing Database Operations with CORS

Once the connection is established, you can perform various database operations. For this example, let's create an endpoint that retrieves data from the Oracle Database.

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

connection.execute(

'SELECT * FROM your_table',

(err, result) =>{

if (err) {

console.error('Error executing query:', err.message);

return;

}

res.json(result.rows);

}

);

});

Replace 'your_table' with the actual table name you want to query.

Step 5: Starting the Server To start the server and listen on a specific port, add the following code snippet:

app.listen(port, () => {

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

});

Conclusion:

Congratulations! You have successfully connected your Node.js application to an Oracle Database while incorporating CORS to handle cross-origin requests. By combining the power of Node.js, Oracle Database, and CORS, you can build secure and data-driven applications.


Example code:

const express = require('express');

const oracledb = require('oracledb');

const cors = require('cors');

const app = express();

const port = 3000;

app.use(cors());

app.use(express.json());



// Configure Oracle database connection

const dbConfig = {

user: 'system',

password: 'admin',

connectString: '//localhost:1521/XE'             //for oracle 21XE

};



// Define the route to fetch(retrive) data from the "users" table

app.get('/api/users', async (req, res) => {

try {

// Create a connection to the Oracle database

const connection = await oracledb.getConnection(dbConfig);



// Execute the SQL query to fetch data from the "users" table

const result = await connection.execute('SELECT * FROM users');



// Close the database connection

await connection.close();

res.json(result.rows);



} catch (error) {

console.error('Error executing SQL statement:', error);

res.status(500).send('Failed to fetch data from the database');

}

});

app.listen(port, () = > {

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

});

node server.js

Server running on port 3000


http://localhost:3000/api/users

[["user1","password1"],["user2","password2"]]

Post a Comment

0 Comments