NODE.js Insert into SQL Server - node.js

I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.

Related

Node.js invalid argument - argument must be of type string

I want to create a node.js app that will pull data from a database and send it to a Google Chatbot. This is the app that queries my database, I have another file that will send the data to Google Chatbot. However, running the code to get the data gives me an invalid argument error.
What am I doing wrong?
enter image description here
var sql = require('mssql');
var DailySummary = require();
DailySummary.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'password',
server: 'localhost',
database: 'SupportCaseMonitor'
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('SELECT * FROM Message_DailySummary', function (err, recordset) {
if (err) console.log(err)
res.send(recordset);
});
});
});
var server = DailySummary.listen(5000, function () {
console.log('Server is running..');
});
function exitProcess() {
process.exit(0);
});
The problem here:
var DailySummary = require();
Likely what you meant to write was instead:
const express = require('express');
const DailySummary = express();

Cors proxy issues within server.js file(react, express,sql)

I have made a basic fullstack website using mssql and express. Originally the get routes worked but after implementing the post route they have stopped.
I believe I am receiving a cors error which is.
Proxy error: Could not proxy request /admin-view-users from localhost:3000 to http://localhost:5000/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
my server.js
const express = require("express");
const sql = require("mssql");
var cors = require("cors");
const path = require("path");
var bodyParser = require("body-parser");
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
const config = {
user: "sas",
password: "Mypassword456",
server: "DEVSQL_2014", // You can use 'localhost\\instance' to connect to named instance
database: "TestDBWebsite"
};
//AdminView users just pulls the users from the database
app.get("/admin-view-users", cors(), function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/admin-view-users", function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/user-questions", function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Questions ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
});
});
//
var jsonParser = bodyParser.json();
app.use(express.bodyParser());
app.post("/admin-Add-Users", jsonParser, function(request, response) {
var email = req.body.email;
var password = req.body.password;
var request = new sql.Request();
// query to the database and get the records
console.log(email, password); // your JSON
// echo the result back
console.log(request.body);
request.query(
"insert into Login (email, password) values ('" +
email +
"','" +
password +
"')",
function(err, recordset) {
if (err) console.log(err);
}
);
response.send({ message: "Success" });
});
app.listen(port, () => `Server running on port ${port}`);
I have included "app.use(cors());" which I assumed woudl resolve this but it has not.
Please advice if you can .
The first thing that comes up to my mind is the double use of CORS.
You are putting it uptop in the middleware stack and then calling it again in here:
app.get("/admin-view-users", cors(), function(req, res) {
Please try using this only once:
https://www.npmjs.com/package/cors

How to correctly retrieve data using an node api of a sqlite3 database

I am coding a simple node.js application that retrieves store data from a sqlite3 database. I coded the API using express and when I test it with curl it doesn't retrieve the data.
I have tested the SQL model and it works.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('********', (err) => {
if (err) {
return console.error(err.message);
}
console.log('Connected to the in-memory SQlite database.');
});
function recordNotFound(message) {
Error.call(this);
this.message = message;
this.status = 404;
}
var Users = function () {};
Users.prototype.getAll = function(callback) {
let sql = 'SELECT * FROM users';
db.all(sql, [], function(err, rows) {
if (err) {
console.log('chao1');
callback(err, null);
} else {
console.log('chao2');
callback(err, rows);
}
});
};
var users = new Users();
users.getAll(function(err, rows) {
console.log(rows);
callback(null, 1);
})
});
Also, when doing
SELECT * FROM users;
in the sqlite3 terminal it retrieves the information correctly.
However, in the file user_api_router.js I have,
var express = require('express');
userApiRouter = express.Router();
var Users = require('../model/users_sql_model')
var users = new Users();
userApiRouter.get('/', function(req, res) {
users.getAll(function(err, result) {
if (err) {
console.log('control1');
res.status(500).json({message: 'Error retrieving records!'});
return;
}
res.status(200).json(result);
});
});
And in the index.js file I have,
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
var usersApiRouter = require('./app/router/user_api_router');
app.use('/v1/user', usersApiRouter);
var port = 3000;
app.listen(port, function(){
console.log('listening on port ' + port);
});
When I run index.js and type
curl http://localhost:3000/v1/user
It says,
{"message":"Error retrieving records!"}
I don't know what to do to retrieve the records correctly using curl. Help me please!

Express.js nested routes without parameters

I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};

Inserting in mongodb with nodejs

I'm trying to insert some data in my mongodb with nodejs whenever a socket is emitted. Here is the code:
io.sockets.on( "connection",function( socket ){
socket.on( "send", function( data ) {
console.log(data.name + " and the content is: " + data.content);
mongodb.connect( "mongodb://127.0.0.1", function( err, db ) {
if(err) throw err;
var to_be_inserted = {name: data.name,content: data.content};
db.collection("chat").insert(to_be_inserted,function(err,objects){
if(err) throw err;
});
})
})
})
However whenever I go to my mongo console and type
db.chat.find()
I cannot find the inserted record. I'm sure that I have mongod open and I'm sure that the socket is emitted. Moreover the consoloe.log before the insertion does work.
Here is my mongo client
var mongodb = require("mongodb").MongoClient;
My console which runs the nodejs server does not log any error.
You should specify a database name (here: myDatabase ) and a port number (for safety).
mongodb.connect("mongodb://127.0.0.1:27017/myDatabase", function( err, db ) {
When searching the record in the mongo shell try:
use myDatabase
db.chat.find()
You forget to include the port number and database of mongodb,
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
}
try this code
var MongoClient=require('mongodb').MongoClient;
var Server=require('mongodb').Server;
var mongoc=new MongoClient(new Server("localhost",27017));
mongoc.open(function(err)
{
db.collection(<collection_name>).insert(<query>,function(err,result)
{
});
const http = require('http');
const hostname = '127.0.0.1';
const port = 8081;
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
app.use(bodyParser.json());
app.get('/get', function (req, res) {
res.send('Hello World')
})
var data = {
title: 'my title',
content: 'my content'
};
// This responds a POST request for the homepage
app.post('/say/:userid', function (req, res) {
var queryParameter=JSON.stringify(req.query);
res.send('Hello POST'+req.params.userid+""+queryParameter);
})
app.post('/insert', function (req, res) {
console.log(req.body);
res.send('Hello POST'+JSON.stringify(req.body));
/* var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017"; */
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbase = db.db("mydb");
var myobj = { name: JSON.stringify(req.body.name), address:JSON.stringify(req.body.address) };
dbase.collection("student").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");

Resources