Why can't I connect to SQLServer uisng NodeJS? - javascript

I'm new using Node JS and now I'm creating a project that connects to SQL Server, but when I use the command node Database\connect.js It simply does do nothing, as it should do a console.log that it did connect or it didn't.
Here is my package.json
{
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"tedious": "^14.0.0"
},
"name": "weather-nodejs-apirest",
"version": "1.0.0",
"main": "connect.js",
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
And here is my connect.js
var Connection = require('tedious').Connection;
var config = {
server: 'SERVERNAME',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: 'password'
}
},
options: {
database: 'weather_app',
// instanceName: 'Sqlexpress',
rowCollectionOnDone: true,
useColumnNames: false
}
}
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log(err);
} else {
console.log('Connected');
}
});
module.exports = connection;

The connection.on(...) method will not initiate the database connection itself. It only runs when the application initiates it using connection.connect() method.
Since you are exporting connection to the outside from connect.js, You should import and initiate the connection somewhere (mostly in application entry point),
const connection = require('path/to/connect.js');
// initiate
connection.connect();
Doc: http://tediousjs.github.io/tedious/getting-started.html

Related

Error: "subscription" defined in resolvers, but not in schema

index.js
const {GraphQLServer, GrphQLServer, PubSub } = require('graphql-yoga');
const db = require('./db');
const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation');
const subscription = require('./resolvers/Substription')
const pubsub = new PubSub();
const typeDefs=`
type Query{
me:User!
signlevalue(name:String):String
sum(marks:[Int]):Int!
user:[User]
}
type Mutation{
createUser(id:ID,name:String,email:String):[User]
}
type User{
id:ID
name:String
email:String
age:Int
}
type Subscription{
count:Int
}
`
const resolvers={
Query,
Mutation,
subscription
}
const server= new GraphQLServer({
typeDefs,
resolvers,
context:{
db,
pubsub
}
})
server.start(()=>{
console.log('servr is running on port 4000');
})
Substription.js
const Subscription={
count:{
subscribe(parent,args,{pubsub},info){
let count=0;
setInterval(() => {
count++;
pubsub.publish('count',{
count:count
})
}, 1000);
return pubsub.asynsIterateor('count')
}
}
}
module.exports = Subscription;
package.json
{
"name": "sql",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon src/index.js --ext js,graphql --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"express": "^4.17.1",
"express-graphql": "^0.11.0",
"graphql": "^15.3.0",
"graphql-yoga": "^1.18.3",
"lodash": "^4.17.20"
}
}
i am a biggner in graphQL word and i dont know what is wrong here because i have defined subsciption in schema but it still gives me error "subscription" defined in resolvers, but not in schema i have searched it but not finding any solution i am following andrew mead course from udemy
your import name is "subscription" (small s) while in your type defination you are using "Subscription"(large s)
use this
const Subscription = require('./resolvers/Substription')

How to save data using mongodb query in middleware in nodejs

I want to save data using mongodb query using middleware in node.js. please provide some code with example?
Try this. It works both for insert and update (upsert).
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const mongodb_url = process.env.MONGO_URL || "mongodb://localhost:27017";
const mongodb_dbname = 'test_db';
const port = process.env.PORT || 3006;
const app = express();
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json({ extended: true}));
app.post('/api/post/:identifier', (req, res) => {
const identifier = req.params.identifier;
const content = req.body.payload;
MongoClient.connect(`${mongodb_url}`, { useNewUrlParser: true }, (err, client) => {
if (!err) {
let db = client.db(mongodb_dbname);
db.collection('posts')
.updateOne(
{ identifier: identifier },
{ $set: { content: content } },
{ upsert: true }
)
.then((output) => {
res.status(202).send({ message: "Sent"});
})
.catch((error) => {
res.status(500).send({
error_code: 500,
error_message: `Error while updating data - ${error}`
});
});
client.close();
} else {
res.status(500).send({
error_code: 500,
error_message: 'Error while connecting to database'
});
}
});
});
app.listen(port, () => {
console.log(`API bootstrapped on port ${port}...`);
});
Use the following package.json file:
{
"name": "mongo-upsert",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongodb": "^3.6.0"
}
}
When invoked as localhost:3006/api/post/my-post with a request body containing:
{
"payload": "Hello world"
}
This code is going to upsert a MongoDB document like:
{
"_id" : ObjectId("5f3d272cbd52c9c109ea9baa"),
"identifier" : "my-post",
"content" : "Hello world"
}
Prerequisites for the above code to work:
To have a working installation of mongodb
To have a database named test_db
To have a collection named posts
In this example, we are adding a post content, identified by an identifier, which for the sake of simplicity I have added as a path param in the POST definition.
Install dependencies using npm install.
Run the app using npm start.
Good luck.
Look into W3Schools NodeJS MongoDB.
I don't have enough rep to comment so here's an answer.

Getting 'undefined' while fetching data from an URL using request module in Nodejs

I am trying to simply use the request module and fetch the data from an API. It looks like no error is there even though I am getting 'undefined'. I am confused as it is because of any VS code settings or what.
The editor I am using is - VS Code
Dependency list -
{
"name": "weather-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"http": "0.0.0",
"request": "^2.88.0"
}
}
Node and npm version -
C:\Users\lenovo>node -v
v10.16.0
C:\Users\lenovo>npm -v
6.9.1-next.0
const request = require('request')
const url = 'https://api.darksky.net/forecast/5a6c29e0d9c879cef11d4d5de29d7d78/37.8267,-122.4233'
request({ url: url }, (error, response) => {
console.log(response)
})
The output I am getting - undefined.
The output I should get - JSON data from API request
I made a check on this and it works fine, please correct your code and try again
const request = require('request')
const url = 'https://api.darksky.net/forecast/5a6c29e0d9c879cef11d4d5de29d7d78/37.8267,-122.4233'
request({ url: url }, (error, response) => {
if (error) {
console.log(error)
}
console.log(response.body)
})

Issue accessing database server/functions from entry file.

So I connect to my database when the server is started. Then when my site is being loaded in the entry js file, I require the file that has functions I can call to run some query. My bundler tries to build the file containing the database functions and everything crashes. I think the root of the problem is that my databasemanger.js file is being built(even though it shouldn't) but I don't know how to resolve the issue.
server.js
'use strict';
const express = require('express');
const app = express();
const path = require("path");
var Vue = require('vue');
var database = require('./databasemanager');
// Create connection to database
var DIST_DIR = path.join(__dirname, "dist"), PORT = 3000;
app.use(express.static(DIST_DIR));
app.get("*", function (req, res) {
res.sendFile(path.join(DIST_DIR, "index.html"));
});
// var connection = new Connection(config);
database.connect();
app.listen(3000);
here is my databasemanger.js
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var ableToRun = false;
var config =
{
userName: '.....', // update me
password: '....!', // update me
server: '......', // update me
options:
{
database: '.....' //update me
, encrypt: true
}
};
var connection;
function connect() {
connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on('connect', function (err) {
if (err) {
console.log(err);
return false;
}
else {
ableToRun = true;
queryDatabase();
return true;
}
}
);
};
function queryDatabase() {
// Read all rows from table
request = new Request(
"SELECT * FROM STUDENT",
function (err, rowCount, rows) {
if (err) {
console.log(err);
}
console.log("rowCount::" + rowCount);
console.log(rows)
// process.exit();
}
);
request.on('row', function (columns) {
columns.forEach(function (column) {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
};
function unionQuery() {
// Read all rows from table
request = new Request(
"SELECT * FROM STUDENT",
function (err, rowCount, rows) {
if (err) {
console.log(err);
}
console.log("rowCount::" + rowCount);
console.log(rows)
// process.exit();
}
);
request.on('row', function (columns) {
columns.forEach(function (column) {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
};
module.exports = {
connect: connect,
unionQuery: unionQuery
}
mywebpack.config is setup like this::
var path = require("path");
var DIST_DIR = path.join(__dirname, "dist"),
CLIENT_DIR = path.join(__dirname, "src");
module.exports = {
context: CLIENT_DIR,
entry: "./index",
output: {
path: DIST_DIR,
filename: "bundle.js"
},
resolve: {
extensions: ['', '.js']
}
};
In my index.js file I have this line
let databasemanager = require ('../databasemanager');
which seems to be causing the issue. I need this here because I want to run the commands here.
Part of the error on the console I get is::
> webpack && npm start
Hash: 7cfb6092af955d7afa54
Version: webpack 2.1.0-beta.22
Time: 1458ms
Asset Size Chunks Chunk Names
index.html 1.69 kB [emitted]
bundle.js 1.17 MB 0 [emitted] main
[144] ../databasemanager.js 5.78 kB {0} [built]
[322] ./index.js 555 bytes {0} [built]
+ 321 hidden modules
ERROR in ../~/tedious/lib/connector.js
Module not found: Error: Can't resolve 'net' in '/Users/nishantrimal/Desktop/DataBase/WebsistePresent/node_modules/tedious/lib'
# ../~/tedious/lib/connector.js 17:10-24
# ../~/tedious/lib/connection.js
# ../~/tedious/lib/tedious.js
# ../databasemanager.js
# ./index.js
ERROR in ../~/tedious/lib/connector.js
Module not found: Error: Can't resolve 'dns' in '/Users/nishantrimal/Desktop/DataBase/WebsistePresent/node_modules/tedious/lib'
# ../~/tedious/lib/connector.js 18:10-24
# ../~/tedious/lib/connection.js
# ../~/tedious/lib/tedious.js
# ../databasemanager.js
# ./index.js
Lastly, my pacakage.json is setup like this
{
"name": "WebsistePresent",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "webpack && npm start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.6.0",
"express": "^4.16.2",
"lodash": "^4.17.4",
"tedious": "^2.1.1",
"uniq": "^1.0.1",
"vue": "^2.5.6"
},
"devDependencies": {
"eslint": "^4.11.0",
"file-loader": "^1.1.5",
"webpack": "^2.1.0-beta.22",
"webpack-node-externals": "^1.6.0"
}
}
Any help would be greatly appreciated!!

TypeError: sql.Connection is not a function Node.js

I am very beginner with node.js and javscript itself. I am trying to establish a basic connection to SQLServer but I am getting the following error:
TypeError: sql.Connection is not a function
I am following the recommendations of the mssql package git repository
//get an instance of sqlserver
var sql = require('mssql');
//set up a sql server credentials
var config = {
server: 'localhost',
database: 'trafiyadb',
user: 'jhonycage',
password: 'juan1014',
port: 1433
};
function con() {
var dbConn = new sql.Connection(config);
dbConn.connect().then(function(){
console.log("connected")
}).catch(function (err) {
console.log(err);
})
}
con();
and this is the package.json
{
"name": "trafiyaapi",
"version": "1.0.0",
"description": "",
"main": "server.js\u001b[A\u001b[B\u001b[B\u001b[B\u001b[A\u001b[B",
"dependencies": {
"express": "^4.15.2",
"body-parser": "^1.17.1",
"mssql": "^4.0.4",
"jsonwebtoken": "^7.4.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC"
}
I am just executing
$node server
I must be doing something wrong, how can i connect to database?
In fact, the function Connection doesn't exist. According to the documentation, to connect to a database, you can use the class ConnectionPool, or the method connect.
var dbConn = new sql.ConnectionPool(config);
dbConn.connect(function(err) {
// ...
});
// OR ...
sql.connect(config).then(function(dbConn) {
// ...
})

Categories