I have tried with Joel solution but getting some error. Can anybody tell me where is the problem.
app.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, mysql = require('mysql')
var client = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
});
client.connect();
app.listen(3232);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('login', function(usr, pass){
var TEST_DATABASE = 'mysqltest';
var TEST_TABLE = 'users';
client.query('USE '+TEST_DATABASE);
client.query('SELECT name FROM '+TEST_TABLE+' WHERE user = "'+usr+'" AND password = "'+pass+'"', function(err, results) {
if (err) throw err;
console.log(results[0]); // [{1: 1}]
socket.emit('retuLogIn',results[0]['name']);
});
});
socket.on('disconnect', function(){
console.log('Server has disconnected');
});
});
index.html
<html>
<title>WebSocket Client Demo [socket.io]</title>
<script src="http://localhost:3232/socket.io/socket.io.js"></script>
<script>
function connect() {
try
{
var socket = io.connect('http://localhost:3232/');
socket.on("connect",function(){
document.getElementById('status').innerHTML ="Browser has connected to the app server";
socket.emit('login', document.getElementById('txtUser').value,
document.getElementById('txtPass').value);
});
socket.on('retuLogIn', function (data) {
document.getElementById('status').innerHTML = 'Welcome '+data;
});
}
catch(err)
{
document.getElementById('status').innerHTML = err.message;
}
}
</script>
<body>
<h1>WebSocket Client Demo</h1>
<div><p id="status">Enter user and password to Log-In</p></div>
<label>User :</label>
<input id="txtUser" type="text" maxlength="10" />
<label>Password :</label>
<input id="txtPass" type="text" maxlength="10" />
<button id="connect" onClick='connect()'/>Log-In</button>
</body>
</html>
When i try to run the app.js file within node.js it will give me the following error:
C:\Program Files (x86)\nodejs>node "C:\Program Files (x86)\nodejs\app.js" info - socket.io started
C:\Program Files (x86)\nodejs\app.js:6 var client = mysql.createConnection({ ^ TypeError: Object # has no method 'createConnection' at Object. (C:\Program Files (x86)\nodejs\app.js:6:24) at Module._compile (module.js:449:26) at Object..js (module.js:467:10) at Module.load (module.js:356:32) at Function._load (module.js:312:12) at module.js:487:10 at EventEmitter._tickCallback (node.js:238:9)
C:\Program Files (x86)\nodejs>
I can not understand where is the problem. I have checked mysql module installed.
Please help to sort-out the problem.
#Chandan,
I had the same error (briefly)
TypeError: Object #<Object> has no method 'createConnection'
Checked https://github.com/felixge/node-mysql but no one else is reporting it as an issue.
Installing the latest (alpha) version of the node mysql module solved the problem:
npm install mysql#2.0.0-alpha3
YMMV.
If you figure it out without updating your mysql module please inform us.
Related
I am creating a publishing application that needs to use communication between React and MySQL database to send information back and forth. Using Express as my JS server. The server code looks as follows:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'ArticleDatabase',
port: 3300,
socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
});
// Initialize the app
const app = express();
app.use(cors());
appl.post('/articletest', function(req, res) {
var art = req.body;
var query = connection.query("INSERT INTO articles SET ?", art,
function(err, res) {
})
})
// https://expressjs.com/en/guide/routing.html
app.get('/comments', function (req, res) {
// connection.connect();
connection.query('SELECT * FROM articles', function (error, results,
fields) {
if (error) throw error;
else {
return res.json({
data: results
})
};
});
// connection.end();
});
// Start the server
app.listen(3300, () => {
console.log('Listening on port 3300');
});
And my React class looks as follows:
class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
author: '',
text: ''
}
}
handleSubmit() {
// On submit of the form, send a POST request with the data to the
// server.
fetch('http://localhost:3300/articletest', {
body: JSON.stringify(this.state),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(function (response) {
console.log(response);
if (response.status === 200) {
alert('Saved');
} else {
alert('Issues saving');
}
});
}
render() {
return (
<div>
<form onSubmit={() => this.handleSubmit()}>
<input type = "text" placeholder="title" onChange={e =>
this.setState({ title: e.target.value} )} />
<input type="text" placeholder="author" onChange={e =>
this.setState({ author: e.target.value} )} />
<textarea type="text" placeholder="text" onChange={e =>
this.setState({ text: e.target.value} )} />
<input type="Submit" />
</form>
</div>
);
}
}
So fairly standard stuff that I found in online tutorials. I can search my database and display fetched info no problem, but not the other way around. When I try to take input from the <form> tag nothing is inserted into my database but instead I get this error:
[Error] Fetch API cannot load
http://localhost:3000/static/js/0.chunk.js due to access control
checks.
Error: The error you provided does not contain a stack trace.
Unhandled Promise Rejection: TypeError: cancelled
I understand that this has something to do with access control but since I am already using cors and can successfully retrieve data from the database, I am not sure what I am doing wrong. Any suggestions will be greatly appreciated. Thank you in advance.
You'll need to isolate the problem by first verifying that your service point is CORS Enabled. In order to focus solely on CORS functionality, I would remove the MySQL code temporarily.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', function(req, res){
var root = {};
root.status = 'success';
root.method = 'index';
var json = JSON.stringify(root);
res.send(json);
});
app.post('/cors', function(req, res) {
var root = {};
root.status = 'success';
root.method = 'cors';
var json = JSON.stringify(root);
res.send(json);
})
// Start the server
app.listen(3300, () => {
console.log('Listening on port 3300');
});
One you have server listening on port 3300, run the following PREFLIGHT command at the terminal.
curl -v \
-H "Origin: https://example.com" \
-H "Access-Control-Request-Headers: X-Custom-Header" \
-H "Acess-Control-Request-Method: POST" \
-X OPTIONS \
http://localhost:3300
If the preflight request is successful, the response should include Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers
Now run the POST method.
curl -v \
-H "Origin: https://example.com" \
-H "X-Custom-Header: value" \
-X POST \
http://localhost:3300/cors
If the post request is successful, the response should include
Access-Control-Allow-Origin
If everything looks good, your server is okay. You then need to try the post method from your iOS app.
NOTE. I would also be suspicious of using cors on localhost. I would map 127.0.0.1 to a domain and then have the app use that domain instead. If you are on Linux or Mac, you modify /etc/hosts. For Windows it's c:\windows\system32\drivers\etc\hosts
Try explicitly whitelisting the server that is making the request:
const whitelist = ['http://localhost:3000']; // React app
const corsInstance = cors({
origin: (origin, callback) => {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
});
application.use(corsInstance);
https://expressjs.com/en/resources/middleware/cors.html#configuring-cors-w-dynamic-origin
You need to add event.preventDefault() at the end of your handleSubmit method (check this example https://stackblitz.com/edit/react-forms).
You have to do it for the reason for preventing form default behavior on submit: it tries to synchronously send data to the url it loaded from (since there is no action attribute on it).
For those who may have run into a similar problem, I was able to fix it by dumping express server altogether. I simply used the .php file on the Apache server to insert data into database. Hope it helps somebody.
I am trying to create a simple nodejs code using express and mysql.
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'admin',
password : ''
});
db.connect((err) => {
if(err){
console.log('Error while connecting');
}
console.log('Connected');
});
const app = express();
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
app .listen('4200',() => {
console.log('Server started on port 4200');
});
The response is sent to the browser that says
database created..
but the result it throws is undefined. Also the console that says
Error while creating database is printed
Error I am getting is
[nodemon] restarting due to changes...
[nodemon] restarting due to
changes... [nodemon] starting node index.js
Server started on port 4200
Connected error while creating database
result: undefined
I am not sure on what I am missing out. Please help.
Below code should work fine, try to execute the below code in a .js file. If it works, then we would be sure that nothing wrong in the conf part.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I am not an expert, but added the keyword 'function', like below:
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql11';
db.query(sql, function(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
Try this, it will work
app.get('/createdb',(req, res) => {
db.query('CREATE DATABASE nodemysql11', function(err,result) {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
Try the below line and then run the .js file.
I assume u have done npm install mysql
mv ./node_modules/node-mysql/node_modules/* ./node_modules/
this is my index.html
i'm unable to get output while running npm start in the command prompt
i have tried using localost:8080 and localhost:8080/index.html
but the only output i'm getting is cannot get
<!DOCTYPE html>
<html lang="en">
<head>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/app.js"></script>
<script src="/Scripts/angular/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<form>
Author:
<input type="text" ng-model="author">
<br>
<br> Title:
<input type="text" ng-model="title">
<br>
<br> Body:
<input type="author" ng-model="body">
<br>
<br>
<input type="submit" value="Submit" ng-click="submit()">
</form>
</div>
</body>
</html>
this is my app.js file
i'm unable to get output while running npm start in the command prompt
i have tried using localost:8080 and localhost:8080/index.html
but the only output i'm getting is cannot get
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.submit= function(){
var data = $.param({
book: JSON.stringify({
author: $scope.author,
title : $scope.title,
body : $scope.body
})
});
$http.post("/api/book/", data).success(function(data, status) {
console.log('Data posted successfully');
})
}
});
This is server.js file
i'm unable to get output while running npm start in the command prompt
i have tried using localost:8080 and localhost:8080/index.html
but the only output i'm getting is cannot get
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydb'
});
connection.connect();
app.post('/api/book', function(req, res, next){
var cope = req.body.params;
var query = connection.query('insert into cope set ?', cope, function(err, result) {
if (err) {
console.error(err);
return res.send(err);
} else {
return res.send('Ok');
}
});
});
app.listen(8080);
console.log("listening");
I am trying to connect my react application to MySql database using nodejs but on clicking the submit button it throws me the following error:
POST http://localhost:3000/login 500 (Internal Server Error)
Failed to load http://localhost:3000/login: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise) TypeError: Failed to fetch
Below is my code for my login component and my nodejs file.
Login.js:
import React from "react";
import {Header} from './Header';
export class Login extends React.Component{
constructor() {
super();
this.state = { user: {} };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
//const proxyurl = "https://cors-anywhere.herokuapp.com/";
var self = this;
// On submit of the form, send a POST request with the data to the server.
fetch('http://localhost:3000/login', {
method: 'POST',
body: {
name: self.refs.name,
job: self.refs.job
}
})
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body);
});
}
render(){
return(
<div>
<div id="fm">
<form onSubmit={this.onSubmit} >
<div >
<label>
Username:
<input id="uname" type="text" placeholder="Name" ref="name"/>
</label>
</div>
<div >
<label>
Password:
<input id="upass" type="password" placeholder="Jo b" ref="job"/>
</label>
</div>
<input id="sub" type="submit" value="Submit" />
</form>
</div>
</div>
);
}
}
Connection.js:
var mysql = require('mysql');
var express = require('express');
var app = express();
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
//var sql = "INSERT INTO users (name, job) VALUES ('e211', 'Highway 37')";
//con.query(sql, function (err, result) {
//if (err) throw err;
//console.log("1 record inserted");
//});
});
app.post('/login', function(req, res) {
// Get sent data.
var user = req.body;
// Do a MySQL query.
var query = con.query('INSERT INTO users SET ?', user, function(err, result)
{
// Neat!
});
res.end('Success');
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
On running Connection.js it connects to my database and if I try to insert data directly by writing an insert statement in the Connection.js file and running it, then it inserts into database but if I try to click on submit button on my UI it throws the above error.
Can someone tell me where I have gone wrong and guide me on the same?
You will need to enable CORS on the server this is to avoid any unwanted calls to your server API'S
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});
I want to perform a basic CRUD with mysql and I installed some modules like npm install mysql,npm install path, npm install routes but there is a problem which I'm facing is most middleware error here is my
app.js
var express = require('express');
var routes = require('./routes');
var http = require('http')
var path = require('path');
//load customers route
var customers = require('./routes/customers');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
// all environments
app.set('port', process.env.PORT || 80);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : 80, //port mysql
database:'nodejs'
},'pool') //or single
);
app.get('/', routes.index);
app.get('/customers', customers.list);
app.get('/customers/add', customers.add);
app.post('/customers/add', customers.save);
app.get('/customers/delete/:id', customers.delete_customer);
app.get('/customers/edit/:id', customers.edit);
app.post('/customers/edit/:id',customers.save_edit);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and here is other customer.js
exports.list = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM customer',function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
//console.log(query.sql);
});
};
exports.add = function(req, res){
res.render('add_customer',{page_title:"Add Customers - Node.js"});
};
exports.edit = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM customer WHERE id = ?',[id],function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.render('edit_customer',{page_title:"Edit Customers - Node.js",data:rows});
});
});
};
exports.save = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
req.getConnection(function (err, connection) {
var data = {
name : input.name,
address : input.address,
email : input.email,
phone : input.phone
};
var query = connection.query("INSERT INTO customer set ? ",data, function(err, rows)
{
if (err)
console.log("Error inserting : %s ",err );
res.redirect('/customers');
});
});
};
exports.save_edit = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
var id = req.params.id;
req.getConnection(function (err, connection) {
var data = {
name : input.name,
address : input.address,
email : input.email,
phone : input.phone
};
connection.query("UPDATE customer set ? WHERE id = ? ",[data,id], function(err, rows)
{
if (err)
console.log("Error Updating : %s ",err );
res.redirect('/customers');
});
});
};
exports.delete_customer = function(req,res){
var id = req.params.id;
req.getConnection(function (err, connection) {
connection.query("DELETE FROM customer WHERE id = ? ",[id], function(err, rows)
{
if(err)
console.log("Error deleting : %s ",err );
res.redirect('/customers');
});
});
};
every time when i go to cmd and run the nodo app the error occur
Error: Most middleware (like logger) is no longer bundled with Express and must
be installed separately. Please see https://github.com/senchalabs/connect#middle
ware.
at Function.Object.defineProperty.get (C:\Users\Tahir\Desktop\node_modules\e
xpress\lib\express.js:89:13)
at Object.<anonymous> (C:\Users\Tahir\Desktop\nodecrud-master\app.js:23:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
any body help to figure out where is the issue is ??
this code depend on express 3.4.0 version... it not work on express 4.x then express 4.x upgrade some package and middleware...... logger('dev') not work... var logger=require('morgan');... i give some more idea
uninstall express4 and express-generator
like
uninstall
-------------
npm uninstall express -g
npm uninstall express-generator -g
install
---------
npm install express#3.4.0 -g
npm install express-generator -g
npm express -e appname (this is express generator)
>cd appname
appname>npm install
appname>npm install mysql
appname>npm install express-myconnection
after to replace all ur code copy and paste it
then run
appname>node app.js
all the best ........... is code really help u..