Cannot GET error using angular js node.js and mysql - mysql

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");

Related

Sending data from html form to mysql table using node.js

I am trying to send data from my form to mysql database. My table has three columns minus the id column
This is the html for the form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>contact form</title>
</head>
<body>
<div id="page">
<form method="post" action="/myaction">
<label for="name">Enter name: </label>
<input id="name" type="text" name="name" value="<%= qs.person %>"> <br><br>
<label for="age">Enter age: </label>
<input id="age" type="number" name="age" value="<%= qs.year %>"><br><br>
<label for="department">Enter department: </label>
<input id="dept" type="text" name="department" value="<%= qs.dept %>"><br><br>
<input type="submit" value="OK">
</form>
<!--site javascript included-->
<script src="jquery-3.2.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="site.js"></script>
</div>
</body>
</html>
this is my node.js code, app.js:
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('view engine', 'ejs');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var con = mysql.createConnection({
host: "localhost",
user: "Name",
password: "XXXXXXXXXXXX",
database: "mydb"
});
app.get('/contact', function (req, res) {
res.render('contact', { qs: req.query });
});
app.post('/myaction', urlencodedParser, function (req, res) {
console.log(req.body);
var name = req.body.name;
var age = req.body.age;
var department = req.body.department;
con.connect(function (err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO 'customers' (name, age, department) VALUES (name, age, department)";
con.query(sql, function (err) {
if (err) throw err;
console.log("One record inserted");
});
});
res.render('contact-success', { data: req.body });
});
app.listen(3000, function () {
console.log('server running on port 3000');
});
When I enter some values into my form and run it, I get this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''customers' (name, age,
department) VALUES (name, age, department)' at line 1
I'm finding it difficult to figure it out. Any help please!!!
You should not add quotes around the table name.
Check on this.

hot to access username present in login.html to index.js in node.js

i am accessing the username field from the login.html file present in public folder to index.js file which is outside of public folder.
here is my login.html code which is in public folder
<!DOCTYPE html>
<html>
<head>
<title>login</title>
</head>
<body>
<h2> login to chat application </h2>
<form method = "post" action='/user'>
<div class="container">
<label><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="name" >
<button type="submit">Login</button>
</div>
</div>
</form>
</body>
</html>
here is my index.js file which is outside of public folder and i a accessing through route /user.
var express = require('express');
var socket = require('socket.io');
var mongoose = require('mongoose');
var app = express();
var dbPath = "mongodb://localhost/chat";
// command to connect with database
db = mongoose.connect(dbPath);
mongoose.connection.once('open', function() {
console.log("database connection open success");
});
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
app.get('/user', function(req,res){
res.sendFile(__dirname + '/public/login.html');
})
app.post('/user', function(req,res){
if(req.body.name === undefined){
console.log("user not found");
}
else{
console.log("upto here")
res.sendFile(__dirname + '/public/index.html');
}
})
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
socket.on("typing", function (data){
socket.broadcast.emit("typing", data);
});
});
i have chat application accesing username from frontend page and using it to the chat file.
here i am unable to accessing the name="username" field to req.body.username please rectify me.
You need to use the body-parser package : https://www.npmjs.com/package/body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

node js getting the image from the mysql and show in html page

this is my html code for getting an image from the mysql database table
<html ng-app="imgApp">
<head>
<title></title>
<script type="text/javascript" src="public/javascripts/angular.js"></script>
<script type="text/javascript" src="public/javascripts/imgController.js"></script>
</head>
<body ng-controller="imgController">
<img data-ng-repeat="data:image/png;base64,{{base64String}}">
<p>{{variable}}</p>
<button ng-click="getImageFunc()">Get data</button>
</body>
</html>
my backend server.js code
is given below i cant get my image in html page .
kindly check this code and correct the errors.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname));
app.use(bodyParser.json());
var mysql = require('mysql')
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'vinoth',
database: 'test'
})
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
app.get('/getimage',function(request,response){
connection.query ('select img from pic ',function(err,result){
console.log(result);
response.send(result);
});
})
app.listen(4000);
console.log("sever listening at port 4000");
Try to set content-type: image/jpeg or image/gif depends on type
app.get('/getimage', function(request, response) {
connection.query('select img from pic ', function(err, result) {
response.writeHead(200, {
'Content-Type': 'image/jpeg'
});
response.send(result); // Send the image to the browser.
});
});

Node.js posting undefined

I am trying to post and insert data from html form using node.js but I am having problem posting data from HTML form to node.js and extracting the data passed it always undefined for inserting in database using node-mysql I am new with node.js
Here is my app.js code
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json()
var sql = require('mysql');
var connection = sql.createConnection({
host : 'localhost',
user : 'root',
password : '',
port : '3306',
database : 'node'
});
server.listen(3000);
app.get('/nodeThis', function (req, res) {
res.sendFile(__dirname + '/insert.html');
});
app.use(bodyParser.json())
app.post('/nodeThis', jsonParser, function (req, res) {
var post={user_name:req.body.name1,user_what:req.body.what,user_why:req.body.why};
console.log(post);
});
Here is my HTML form:
<html>
<body>
<div>
<form action="/nodeThis" method="post">
<input type="text" name="name1">
<input type="text" name="what">
<input type="text" name="why">
<button class="boom">Submit</button>
</form>
</div>
</body>
</html>

HTML5 page connect mysql database with node.js

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.