Home > Enterprise >  Is it possible to get a MySQL database with parcel-bundler in node.js? Or is there an easier way to
Is it possible to get a MySQL database with parcel-bundler in node.js? Or is there an easier way to

Time:03-31

I'm new to node.js, especially in parcel-bundler. I have already created a server.js to connect with the database like below and run well without problems.

Server.js

const express = require('express');
const mysql = require('mysql');

//Create connection to db
const db = mysql.createConnection({
   host:'localhost',
   user:'root',
   password:'',
   database:'db_webgisapp',
});

//Connect
db.connect((err) => {
   if(err){
       throw err;
   }
   console.log('MySql Connected...')
})

const app = express();

//Select table
app.get('/getdata',(req,res)=>{
   let sql = 'SELECT * FROM tb_testing LIMIT 3';
   let query = db.query(sql,(err,results)=>{
       if(err){
           throw err;
       }
       console.log(results);
       res.send('Fetched...')
   })
})
app.listen('4000',() => {
   console.log('Server started on port 4000')
})

The problems appear when I put Server.js to index.html as a script,

index.html

<!DOCTYPE HTML>
<html  lang="en" data-textdirection="ltr">
   .....
    <!-- BEGIN: Body-->
    <body  data-col="">
    ...
    ...
    ...
    ...

    <script src="./scripts/Server.js"></script>
    <script src="./scripts/Map.js"></script>
    ...
    ...
    </body>
    <!-- END: Body-->
 </html>

And run it as

npm start

So this is my package.json

package.json

"scripts": {
   "start": "parcel index.html",
   "build": "parcel build --public-url . index.html"
},

There's no error in the terminal but I can see 2 errors from inspecting web browser,

  1. Uncaught TypeError: http.ServerResponse is undefined
  2. Error in response Response has been truncated

Usually, I use PHP files to connect with MySQL. But, ParcelJS cannot read PHP files. So, Is someone know how to deal with it? Or there is a better way to get the database and parse it to JSON so I can play with data in parcel-bundler.

Thank you!!!

CodePudding user response:

You can't call a function directly on your node.js server from an HTML file. The HTML file is in the client's browser. The node server is your web server, far away from the client's browser on different computers.

If you want to communicate with the node.js server from the web page, then you use Javascript in the HTML page to make an Ajax call from the Javascript in the web page to the node.js server (An Ajax call is an http request).

  • Related