1

I try to make RESTFUL API with node js and oracle database for my first time

I make a table in the database named "EMPLOYEES" and I add some data there

I make my backend file and I try to get the information in the database and it's worked successfuly

but when I try to make POST to add a new employee I don't get an error and the employee is not added to the database

when I try to test it with POSTMAN I got this result a null object like this {}

I know that I'm missing something

const express = require('express')
const oracledb = require('oracledb');
const bodyPerser=require("body-parser")
const app = express();
const port = 3000;
var password = 'mypassword';
app.use(bodyPerser.json());

async function selectAllEmployees(req, res) {
  try {
    connection = await oracledb.getConnection({
      user: "system",
      password: password,
      connectString: "localhost:1521/XE"
    });

    console.log('connected to database');
    // run query to get all employees
    result = await connection.execute(`SELECT * FROM EMPLOYEES`);

  } catch (err) {
    //send error message
    return res.send(err.message);
  } finally {
    if (connection) {
      try {
        // Always close connections
        await connection.close();
        console.log('close connection success');
      } catch (err) {
        console.error(err.message);
      }
    }
    if (result.rows.length == 0) {
      //query return zero employees
      return res.send('query send no rows');
    } else {
      //send all employees
      //return res.send(result.rows);
      console.log(JSON.stringify(result.rows));
      console.log(result.metaData[0].name);
      let list=[]
      result.rows.forEach(element => {
        let agent = {
          "ID": element[0],
          "EMPNAME": element[1],
          "EMPLASTNAME": element[2],
          "AGE":element[3]
        }
        list.push(agent)
      });
      return res.send(JSON.stringify(list));
      
    }

  }
}

//get /employess
app.get('/employees', function (req, res) {
  selectAllEmployees(req, res);
})

//////////////////post//////////////////////


app.post("/addNewEmployee", async (req, res) => {
   try {
    connection = await oracledb.getConnection({
      user: "system",
      password: password,
      connectString: "localhost:1521/XE"
    });
    console.log('connected to database');
    // I don't know what i'm missing here 
    result=connection.execute(`INSERT INTO EMPLOYEES  VALUES ('${req.body.ID}','${req.body.EMPNAME}','${req.body.EMPLASTNAME}','${req.body.AGE}')`);
    
res.send(result)
  } catch (err) {
    //send error message
    return res.send(err.message);
  } 
  
})

app.listen(port, () => console.log("nodeOracleRestApi app listening on port %s!", port))

1 Answer 1

2

Review node-oracledb examples and make sure you have basic techniques covered e.g. using bind variables. (The way you build your INSERT is open to SQL injection security attacks). Look at how webapp.js uses a connection pool - which you'll need if you have more than one person accessing your service.

Make sure you commit the data after inserting.

Add an 'await' before your connection.execute() for INSERT, something like:

result = await connection.execute(`INSERT INTO EMPLOYEES VALUES (:id, :empname, :emplastname, :age)`,
    [req.body.ID, req.body.EMPNAME, req.body.EMPLASTNAME, req.body.AGE],
    {autoCommit: true}
);

Do some debugging and see what is not working.

Avoid using SYSTEM for testing. Create a 'normal' (non privileged) user: https://blogs.oracle.com/sql/how-to-create-users-grant-them-privileges-and-remove-them-in-oracle-database

Finally check out this series on creating a REST service with node-oracledb:

https://blogs.oracle.com/oraclemagazine/build-rest-apis-for-nodejs-part-1

https://github.com/oracle/oracle-db-examples/tree/master/javascript/rest-api

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your time and for your help, the problem is solved thank you one more time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.