2

Trying to use mssql with React.

If I write a normal js file with the

var sql = require("mssql");

const pool = new sql.ConnectionPool({
  user: "sa",
  password: "password",
  server: "localhost", // You can use 'localhost\\instance' to connect to named instance
  database: "master",
  port: 50845,
  options: {
    trustedConnection: true
  }
});

var conn = pool;

conn
  .connect()
  .then(function() {
    var req = new sql.Request(conn);
    req
      .query("SELECT * FROM CRM.CRM.historical_data")
      .then(function(recordset) {
        console.log(recordset);
        conn.close();
      })
      .catch(function(err) {
        console.log(err);
        conn.close();
      });
  })
  .catch(function(err) {
    console.log(err);
  });

and execute it with node <filename.js>, it works perfectly!

But when I try to create a function in ReactJS it throws an error saying

TypeError: createSecureContext is not a function

Below Snippet won't work but will give you glimpse of what my code currently is looking like.

class App extends React.Component {
  fetchData() {
    var sql = require("mssql");

    const pool = new sql.ConnectionPool({
      user: "sa",
      password: "password",
      server: "localhost", // You can use 'localhost\\instance' to connect to named instance
      database: "master",
      port: 50845,
      options: {
        trustedConnection: true
      }
    });

    var conn = pool;

    conn
      .connect()
      .then(function() {
        var req = new sql.Request(conn);
        req
          .query("SELECT * FROM CRM.CRM.historical_data")
          .then(function(recordset) {
            //WANT THIS CONSOLE TO SHOW THE DATA, as I can see in the file when I do `node <filename>`
            console.log(recordset);
            conn.close();
          })
          .catch(function(err) {
            console.log(err);
            conn.close();
          });
      })
      .catch(function(err) {
        console.log(err);
      });
  }

  render() {
    return (
      <div>
        <button onClick={() => this.fetchData()}>PRESS ME</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Dhaval Jardosh
  • 7,151
  • 5
  • 27
  • 69
  • 1
    Did you ever figure this out? I'm trying the same in a react/express app. i'm assuming it's trying to do some type of server-only function in the browser, but don't know how to split it up... or maybe i'm missing sql commands on my server? – K.H. B Jun 19 '19 at 01:10
  • I had to stall this project due to some other reasons, but once I have any updates will post it here. – Dhaval Jardosh Jun 19 '19 at 03:12
  • I have the same problem. – FrenkyB Nov 11 '19 at 11:16

0 Answers0