Requesting tables from MS Sql - Node.js web service - javascript

I am in need of assistance in terms of generating a request to my Microsoft SQL Server via a web service (Built in Node.js).
To summarize the problem at hand, it is as follows: I am currently logging into a MS Sql Server Management with a windows auth account - that is all find and dandy however, I am now trying to build a web service that allows for selects and transacts of some tables which is where I am running into issues now specifically in terms of logging in and pulling data to the web service.
Code
var express = require('express'); var app = express();
app.get('/',function(req,res) {
const sql = require('mssql');
// Connection Path
const myServerPath = String("xxxx\\WS1SQLEXPRESS");
// Connection String Parameter
const config = {
// User Login Details - Windows Auth or General User Account
user : 'xxxx-xxx\\AdrianH',
password: 'xxxxxx',
// Server path to connect to
server : myServerPath,
// Database
datebase: 'plex',
options : {
trustedConnection: true
}
};
sql.connect(config,function(err) {
if (err) console.log(err);
// Create Request Object
var request = new sql.Request();
// Query the Database
request.query('USE plex; SELECT * FROM [plex].[dbo].[tblWorkCenters]',function(err,recordset) {
if (err) console.log(err)
// send records as response
res.send(recordset);
});
});
});
// Start Server and listen on //http://localhost:8001/
var server = app.listen(3213,function(){
console.log('Server is running...');
});
I have hid sensitive information, here is the error code
{ ConnectionError: Login failed for user ''.
at Connection.tedious.once.err (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.processLogin7Response (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\Users\adrianh\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:198:13)
at Message.message.on (C:\Users\adrianh\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:203:15)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user ''.
at ConnectionError (C:\Users\adrianh\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\Users\adrianh\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:198:13)
at Parser.parser.on.token (C:\Users\adrianh\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:198:13)
at addChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:240:10)
at Parser.Transform.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_transform.js:139:32)
at doneParsing (C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1399:37)
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:546:11)
at Request.query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1335:12)
at C:\Users\adrianh\Desktop\JEC_Current_Projects\WebService\WCWebServiceIOS.js:30:13
at _poolCreate.then.catch.err (C:\Users\adrianh\node_modules\mssql\lib\base.js:287:7)
at process._tickCallback (internal/process/next_tick.js:68:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
** An interesting note to make is in --
(C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
It doesn't actually seem to pass my login information - any help will be greatly appreciated thank you.

If you are trying to connect mssql via windows authentication in node JS use this module.
var mssql = require('mssql/msnodesqlv8
Sample:
var mssql = require('mssql/msnodesqlv8')
var dbConfig = {
server: 'server',
driver: 'msnodesqlv8',
database: 'DBDATA',
port: '1433',
options: {
trustedConnection: true,
debug: {
packet: false,
payload: false,
token: false,
data: false
},
}
};

Related

Can't insert data with mongoDB atlas; Error: queryTxt ETIMEOUT

I've tried to connect to mongodb with node.js, but get the following error. Although I've tried several available solution in this platform, like, changing my DNS to Google's Public DNS, downgrading the node.js driver's version for connection string, but they did not work out for me.
Error: queryTxt ETIMEOUT cluster0.1moqz.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:213:19) {
errno: 'ETIMEOUT',
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'cluster0.1moqz.mongodb.net'
}
here is my server side code:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.1moqz.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
async function run() {
try {
await client.connect();
const userCollection = client.db('myTestDB').collection('users');
const newUser = { name: "username", email: "abc#def.com" };
const result = await userCollection.insertOne(newUser);
console.log("adding new user", result);
}
finally {
await client.close();
}
}
run().catch(console.dir);
Have you added you IP address to the IP Access List?
You must add your IP to the access list in order to access the database (from that IP). To do this:
Go to your MongoDB Atlas page
In the sidebar, under "Security" select "Network access"
Select the "IP Access List" tab
Click the "ADD IP ADDRESS" button
Enter your IP address (there should be a button that does this for you) and click "Confirm"
You should be able to access your MongoDB database after a minute or so

Why Can't I connect SQL Server to my node js

I'm using the 'mssql' npm package to connect my SQL server to my node JS.
I went through a few questions, but it wasn't solved anywhere.
My SQL Server login credentials are-
server type : Database Engine
Server name : DESKTOP-MPF88ST\KUSHAL
authentication : sql server authentication
login : username
password : password
and the database I wanna get is schoolDB
and my code goes something like this
const sql =require("mssql")
const config = {
login: 'username',
password:'password',
server: 'localhost',
database: "schoolDB",
options : {
enableArithAbort: true
},
port : 1433
}
sql.connect(config, (err) => {
if(err){
console.log(err);
}
else {
console.log("Connected")
}
I have my TCP/IP enabled and set up, SQL Server Browser enabled, but it still throws the error-
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.<anonymous> (E:\Kushals\server\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:422:26)
at Connection.emit (events.js:315:20)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ESOCKET'
}
}
How can I solve it ??
Try this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
login: 'username',
password:'password',
database: 'schoolDB',
server: 'DESKTOP-MPF88ST\KUSHAL',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//sample query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
Ensure that the TCP/IP protocol is Enabled as it is disabled by default.
Steps:
Go to Computer management
Under Service and Applications -> SQL Server Configuration Manager
-> SQL Server Network configuration -> click on "Protocols for MSSQLSERVER"
You will see TCP/IP section (to enable right click and enable it)

nodejs MySQL - Server requests authentication using unknown plugin

When attempting to connect to MySQL 8.0.21 server running Ubuntu 20.04 using NodeJS and mysql2 package, I receive the common error below: Server requests authentication using unknown plugin sha256_password I know that mysqljs and mysql2 do not support sha256, so I confirmed my user was setup for mysql_native_password:
ALTER USER 'userName'#'%' IDENTIFIED WITH mysql_native_password BY 'password';
And have confirmed that default_authentication_plugin is set as mysql_native_password.
What makes this a strange issue, is that it only occurs when attempting to unit test the function in Mocha or Jest. When running the app normally, I am able to connect and make DB calls with no issues. To simplify troubleshooting, I created a new app.js file that only calls the dbQuery.getRow() function. Contents of those files and the output is given below.
app.js
(async function main () {
require('dotenv').config({ path: __dirname + '/config/.env' });
const dbQuery = require('./src/js/dbQuery');
let result = await dbQuery.getRow('table', 'c9024a7aead711eab20be6a68ff5219c');
console.log(result);
})();
dbQuery.js
const dbPool = require('./dbPool');
async function getRow(tableName, guid) {
try {
let sql = `
SELECT *
FROM \`${tableName}\`
WHERE guid='${guid}'`;
let [rows] = await dbPool.execute(sql);
return rows[0];
} catch (ex) {
console.log('dbQuery getRow failed with error: ' + ex);
return { error: true, message: ex };
}
}
dbPool.js
const { env } = require('process');
const mysql = require('mysql2/promise');
const dbPool = mysql.createPool({
host: env.DB_HOST,
port: env.DB_PORT,
database: env.DB_NAME,
user: env.DB_USER,
password: env.DB_PW,
// waitForConnections: env.WAIT_FOR_CONNECTIONS.toUpperCase() == 'TRUE' ? true : false,
connectTimeout: 10000,
connectionLimit: parseInt(env.CONNECTION_LIMIT),
queueLimit: parseInt(env.QUEUE_LIMIT)
});
module.exports = dbPool;
Terminal Output - Running the simplified app now returns the row as expected
node app.js
BinaryRow {
guid: 'c9024a7aead711eab20be6a68ff5219c',
name: 'spiffyRow',
displayValue: 'Spiffy Display Value'
}
However, when I attempt to do the same DB call in either Jest or Mocha, I run into the issue again, where it appears mysql2 is attempting to use the wrong authentication plugin.
dbQuery.test.js - currently setup for Mocha, but Jest exposed the same issue
const dbQuery = require('../src/js/dbQuery');
describe('MySQL DB Operations', function () {
describe('#getRow()', function () {
it('Should return row with guid specified', async function (done) {
let result = await dbQuery.getRow('table', 'c9024a7aead711eab20be6a68ff5219c');
if (result.guid == 'c9024a7aead711eab20be6a68ff5219c') done();
else done(result.error);
});
});
});
Terminal Output
npm test
MySQL DB Operations
#getRow()
dbQuery getRow failed with error: Error: Server requests authentication using unknown plugin sha256_password. See TODO: add plugins doco here on how to configure or author authentication plugins.
1) Should return row with guid specified
0 passing (49ms)
1 failing
Thanks in advance for any help, please let me know if any additional information is needed.
When executing the tests, my env variables were not being populated. The fix was as simple as adding require('dotenv').config({ path: 'path/to/.env' }); to my test file. I was thrown off by the error message returned by MySQL. I'm still not sure why MySQL responds stating sha256_password is requested when no credentials are provided, even when the default_auth_plugin is set to mysql_native_password, but once valid credentials were provided everything works as expected.

Not able to send mail from heroku using nodemailer

This is the error I get on heroku when I am trying to send emails from my deployed application.
{ Error: Connection timeout
2018-07-28T21:37:39.586059+00:00 app[web.1]: at SMTPConnection._formatError (/app/node_modules/nodemailer/lib/smtp-connection/index.js:606:19)
2018-07-28T21:37:39.586061+00:00 app[web.1]: at SMTPConnection._onError (/app/node_modules/nodemailer/lib/smtp-connection/index.js:579:20)
2018-07-28T21:37:39.586063+00:00 app[web.1]: at Timeout._connectionTimeout.setTimeout (/app/node_modules/nodemailer/lib/smtp-connection/index.js:261:18)
2018-07-28T21:37:39.586066+00:00 app[web.1]: at ontimeout (timers.js:365:14)
2018-07-28T21:37:39.586067+00:00 app[web.1]: at tryOnTimeout (timers.js:237:5)
2018-07-28T21:37:39.586069+00:00 app[web.1]: at Timer.listOnTimeout (timers.js:207:5) code: 'ETIMEDOUT', command: 'CONN' }
I am using nodemailer version 4.6.7 and here's the code:
'use strict';
const nodemailer = require('nodemailer');
module.exports = {
sendMail: function(email) {
console.log(email)
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport(sails.config.connections.mailer);
// setup email data with unicode symbols
let mailOptions = {
from: '"Medico 👻" <test#testgmail.com>', // sender address
to: email, // list of receivers
subject: 'Test', // Subject line
text: 'Hello world?', // plain text body
html: 'Hello world?' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
});
}
}
I am using the generated app password from google and that works perfectly fine when I run it locally but on heroku it is throwing error.
What am I doing wrong?

Shopify Admin API not working on Google hosted server but works on localhost

My Shopify Admin API not working on Google hosted server but works on localhost. I wonder what am I missing.
I got my order data on localhost but when I upload the code to google server it doesn't work.
I am working on a private app for my shop.
no luck trying to make this works.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const Shopify = require('shopify-api-node');
const shopify = new Shopify({
shopName: 'tinyrabbithole',
apiKey: 'your-api-key',
password: 'your-app-password'
// accessToken: ""
});
shopify.on('callLimits', limits => console.log(limits));
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.getData = functions.https.onRequest((req, res) => {
shopify.order.list({ limit: 5 })
.then( orders => {
console.log(orders);
return res.status(200).send(orders);
})
.catch( err => {
console.log(err);
return res.status(303).send(err);
})
});
{ RequestError: getaddrinfo ENOTFOUND tinyrabbithole.myshopify.com tinyrabbithole.myshopify.com:443
at ClientRequest.req.once.err (/user_code/node_modules/shopify-api-node/node_modules/got/index.js:182:22)
at ClientRequest.g (events.js:292:16)
at emitOne (events.js:101:20)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1025:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'RequestError',
code: 'ENOTFOUND',
host: undefined,
hostname: 'tinyrabbithole.myshopify.com',
method: 'GET',
path: '/admin/orders.json?limit=5',
protocol: 'https:',
url: undefined }
I'll drop this as an answer instead of leaving it in the comments. If you see a getaddrinfo ENOTFOUND error, first make sure you are on the right payment plan. The free tier doesn't allow outgoing API calls.

Categories