Im trying to use mysql in electron but i'm running into this error
TypeError: Invalid data, chunk must be a string or buffer, not object
at Socket.write (net.js:667)
at Protocol.<anonymous> (Connection.js:100)
with this code
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'host address',
user: 'username',
password: 'pw',
database: 'db name',
});
con.connect(err => {
if(err) throw err
})
con.query('select * from BOOKS', (err2, result) => {
if(err2) {
throw err2;
}
console.log(result);
})
if i paste this into a test.js file and run it with node then it runs 100% fine without errors, so im not really sure where im going wrong here
So it turns it my issue had something to do with the fact that I was running Angular on electron. if I put that code inside my Angular code it would error out but if I put it in the index.html it would run fine.
So I just made a little proxy function in the index.html for connecting to the DB and making queries, then i'd jsut call it from inside the Angular app without a problem like window.mysqlQuery(queryString)
Related
I have a Node.js Stackblitz project that I am trying to connect to a remote MySQL database. It is not possible to have a MySQL database within Stackblitz, hence trying the remote approach. However I get "Error: connect ETIMEDOUT" whenever I attempt a connection. Any help or pointers much appreciated.
I am using the code below. The remote database is accessible with the credentials I am using and returning data when used outside of Stackblitz. Is remote database access not possible with Stackblitz or am I missing something?
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
const port = 3010;
const path = require('path');
app.use(express.static('static'));
app.get('/', async function (req, res) {
try {
// create connection
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
});
// query database
const [rows, fields] = await connection.execute('SELECT * FROM `user`');
res.send({
rows,
fields,
});
} catch (err) {
console.log('err:', err);
}
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
For anyone looking for an explanation.
Currently a mysql database cannot reside in StackBlitz. Additionally, neither can it connect to an external mysql database on its own either.
You therefore required a backend API outside of StackBlitz to make the database calls, negating the reason for building the backend on StackBlitz in the first place (IMO). Therefore, the suggested setup currently would be a localhost backend API accessed from a frontend in StackBlitz via an ngrok secure address.
StackBlitz are working on getting basic server requests running in the future. So, watch this space.
I hope this answer helps save others time.
Trying to build a backend database for my React app, and upon trying to import the relevant MySQL libraries, it throws an error. There are no problems when I run it from the terminal, but the moment I put it in, I receive the following error:
./src/data/node_modules/mysql/node_modules/safe-buffer/index.js
Line 1:1: Definition for rule 'node/no-deprecated-api' was not found node/no-deprecated-api
Have not been able to find any solutions while searching.
My code:
import {mysql} from 'mysql'; // Commenting out this one line stops the error
export default function tester() {
/*
const connection = mysql.createConnection({ // Commented out only when import is commented
host: 'localhost',
user: '<username>',
password: '<password>',
database: '<db name>'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
*/
}
To anyone reading this in the future, the solution was to not connect directly to the MySQL server, instead to use Express.
Using mysqljs, I want to query some data from my local db and render them with react.
This is what I did so far:
import React from 'react';
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password: '',
database: 'pep'
});
connection.connect();
var Menu=React.createClass({
data : function (){
connection.query('Select * from '+this.props.table, function(err, rows, fields){
if(err) throw err;
console.log(rows);
})
},
render : function () {
return (
<div>
<button onClick={this.data}>click</button>
</div>
);
}
});
export default Menu;
(Another file is using the Menu component and passing the props to Menu)
Nothing is displayed and it came with this error in the bowser's console:
Connection.js:91 Uncaught TypeError: Net.createConnection is not a function
at Connection.connect (webpack:///./~/mysql/lib/Connection.js?:91:13)
at eval (webpack:///./src/Menu.js?:24:12)
at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:2983:2)
at __webpack_require__ (http://localhost:3000/static/js/bundle.js:556:30)
at fn (http://localhost:3000/static/js/bundle.js:87:20)
at eval (webpack:///./src/Combobox.js?:18:13)
at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:3121:2)
at __webpack_require__ (http://localhost:3000/static/js/bundle.js:556:30)
at fn (http://localhost:3000/static/js/bundle.js:87:20)
at eval (webpack:///./src/App.js?:18:17)
Why is that? How can I fix this or what should I do in order to get my data from the db using react?
mysqljs relies on Node's net library. You don't have this API in your browser, so you won't be able to use the library this way without major changes.
You shouldn't establish a direct connection from the client's browser to your backing database anyway, as your mysql database server is not necessarily built for this use case. Instead, publish your data via a dedicated web server as RESTful web services. You could for example use Node.js and the restify framework for that purpose.
I already have WAMP server installed on my machine. Can I be able to access MySQL databases created on WAMP's MySQL using node-mysql module?
Actually, I tried this code, its running without errors but unable to fetch the database(or tables):
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "database_name"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM table_name', function (error, rows, fields) {
console.log('The first field is: ', rows[0].field);
});
});
}).listen(8001);
console.log("running on localhost:8001");
Try adding request.resume(); before your 'end' event handler.
In node v0.10+, streams start out in a "paused" state that allow you to .read() specific sized chunks or you can use them like the old streams by attaching a 'data' event handler which causes the stream to be continuously read from.
Calling request.resume(); will also switch to the old stream mode, effectively discarding the request data (because there are no 'data' event handlers) so that your 'end' event handler will be called.
I have config.js in my nodejs project
var mysql = require('mysql');
var db_name = 'node';
var client = mysql.createClient({
user: 'root',
password: 'pass',
});
client.query('USE '+db_name);
I have used it as config file for the project. How I can use this code to call a mysql query.
I have this code in user.js
var global = require('./config.js');
this.CheckUserValid = function (login, pass) {
var sql = "SELECT * FROM `user` WHERE login = ? AND pass= ?";
global.client.query(sql, [login, pass], function selectResutl(err, results, fields) {
if (!err) return results;
else
throw err;
});
}
TypeError: Cannot call method 'query' of undefined
at Object.CheckUserValid (C:\wamp\www\Node\user.js:6:19)
Can someone help me to let me know how I can do this in better way.Actually I am using asp.net mvc in my past so I have tried it. Do someone tell me the better way to write code in nodejs.
When you require() a file/module, the result you get is whatever the module is exporting through the exports property. Anything else is encapsulated in the module and cannot be accessed from the outside. In your case, at the end of config.js you can add:
exports.client = client;
This way it will be accessible whenever you require() your config.js.
This way of creating modules is defined in the CommonJS spec:
http://commonjs.org/specs/modules/1.0/
http://wiki.commonjs.org/wiki/Modules/1.1
edit: and since commonjs.org seems to be down, here is another link with information about this type of module: http://dailyjs.com/2010/10/18/modules/