MSSQL Connection login failed for user in node js - node.js

i am trying to connect mssql database but i couldnt achieve that.
When i connect mssql on Microsoft SQL Server Management Studio 18;
https://i.stack.imgur.com/6xdI0.png -- Because of Windows Authentication, i have no password. And there is a username field passive as default, also node js doesnt accept default user name. Why? and what i am doing wrong? When i try to execute js file; https://i.stack.imgur.com/Ty0zA.png -- gives an user name error in cmd db.js file;
var sql = require('mssql');
// config for your database
var config = {
user: 'DESKTOP-S9H932R\\CUNEYT',
password: '',
server: 'localhost',
database: 'cuneyt'
};
// 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 borsa', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
package.json file;
{
"name": "mssql_test",
"version": "1.0.0",
"description": "",
"main": "db.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mssql": "^6.3.1"
}
}

OP solved but for anyone having trouble my issue was that I was connecting to a local DB within a domain. I had to add the option to my config object to be like
config:{
user:'xxxx',
password:'xxxx',
server:'servername',
database:'yourdb'
domain:'yourdomainname'}

Related

my nodemon module is not working with node js

Basically, ive got start:"nodemon node.js" node.js is the actual file. but all it does is bring it up in my editor and port 3000 still isnt responding like it would if i typed node node.js every time i edited it. i did everything in the tutorial verbatim looked up the actual docs and searched stack and im still at a stand still, i am new to this and could use some help please,i installed it npm install nodemon --save-dev and would like to be able to do this in the local environment if possible, the modules are there, its just alot to past here, thanks in advance heres my code and such...
edit: when i run it i get
nod#1.0.0 start
nodemon node.js
in the terminal
const http = require('http');
const fs = require('fs');
const server = http.createServer((req,resp)=>{
const url = req.url;
const method = req.method;
{
"name": "nod",
"version": "1.0.0",
"description": "",
"main": "node.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon node.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.15"
}
}
//.........................................................................................
if(url === '/'){
resp.write('<html>');
resp.write('<head><title>first</title></head>')
resp.write('<body>');
resp.write('<form action="/message"npmns npmno method="POST"><input type="text" name="message"><button type="submit">subn</button></form>');
resp.write('</body>');
resp.write('</html');
return resp.end();
}
if(url === '/message' && method=== 'POST'){
// resp.write('<html>');
// resp.write('<body');
const body =[];
req.on('data',(chunk)=>{
body.push(chunk);
})
req.on('end',(data)=> {
let message = body.toString().split('=')[1];
fs.writeFileSync('billy.txt', message);
})
resp.write('<form action="/" method="POST"><button type="submit">butt</button></form>');
// resp.write('</body>');
// resp.write('</html>');
return resp.end();
}
resp.setHeader('content-type','text/html');
resp.write('<html>');
resp.write('<head><title>firsttime</title></head>');
resp.write('<body><h1>hello again</h1></body>');
resp.write('</html>');
resp.end();
})
server.listen(3000);

AWS Lambda in NodeJS error: "Wrong arguments"

Scenario
My React (Gatsby) application requests information from a database to display a list of products.
The database is a Postgres table on AWS RDS, in a VPC.
My aim is for the React application to trigger an AWS Lambda function to retrieve products from AWS RDS.
Error:
In writing my lambda function, I intend to request all products from my table.
The error message I get is TypeError: Wrong arguments
Code:
index.js
const rds = require('./connection.js');
exports.handler = async ( event, context, callback ) => {
await callback(null, rds.getProducts);
};
connection.js
const Pool = require('pg').Pool;
const pool = new Pool({
user: process.env.user,
host: process.env.host,
database: process.env.database,
password: process.env.password,
port: process.env.port,
});
const getProducts = ( request, response ) => {
pool.query(`SELECT * FROM product_list ORDER by id ASC`, ( error, result ) => {
if( error ) throw new Error(error);
response.status(200).json(result.rows);
})
};
module.exports = {
getProducts,
};
package.json
{
"name": "lambda3",
"version": "1.0.0",
"description": "lambda function access rds",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "scott",
"license": "ISC",
"dependencies": {
"pg": "^7.14.0"
}
}
Full error:
{
"errorType": "TypeError",
"errorMessage": "Wrong arguments",
"trace": [
"TypeError: Wrong arguments",
" at RAPIDClient.postInvocationResponse (/var/runtime/RAPIDClient.js:41:18)",
" at complete (/var/runtime/CallbackContext.js:34:12)",
" at callback (/var/runtime/CallbackContext.js:44:7)",
" at /var/runtime/CallbackContext.js:105:16",
" at Runtime.exports.handler (/var/task/index.js:9:11)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Thoughts: I followed the AWS guide on how to upload a NodeJS deployment package. There didn't seem to be an issue with connection.js when testing locally.
Unsure how to debug this as even "AWS Lambda wrong arguments" yields few relevant results.
What I see as the main issue here is how you use the call back.
The callback function accepts two parameters error and the value.
https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
What I think that you are doing wrong here is, passing the function as reference instead of value for e.g rds.getProducts() to get the value.

What is the most simplest way of implementing a DELETE request using axios?

I have been unsuccessful in trying to figure out how to solve the following errors, (1st error:)'OPTIONS http://localhost:3000/lists/5a9dca48cebb5a4e5fc1bfe9 404 (Not Found)' and (2nd error:)'Failed to load http://localhost:3000/lists/5a9dca48cebb5a4e5fc1bfe9: Response for preflight has invalid HTTP status code 404.'.
Initially I defined my code along the same lines as the following: https://github.com/20chix/Hotel_System_Vue.js_Frontend/blob/master/src/components/Hello.vue
Seen quite a number of posts similar to my problem, but neither of their suggested solutions have worked for me.
I'm using Vue.js, Axios and Node.js in the back, my collection is defined as follows in MongoDb:
List: {_id:'', name:'', items:
[ {
title: '',
category: ''
}
]
}
GetList.vue:
methods: {
fetchLists(){
let uri = 'http://localhost:3000/lists';
axios.get(uri).then((response) => {
this.List = response.data;
console.log(this.List[3].items[0]);
console.log(this.List);
});
},
DELETE(a_list, id){
$("#myModal").modal('show');
this.list = a_list;
this._id = id;
},
deleteList : function(_id){
// let uri = 'http://localhost:3000/lists/'+_id;
// this.List.splice(_id, 1);
axios.delete('http://localhost:3000/lists/'+_id)
.then((response) => {
this.fetchLists();
//refreshes Application
// window.location.reload();
})
.catch((error) => {
console.log(error);
});
}
ListController:
exports.delete_a_list = function(req, res)=>{
console.log(req.params);
List.deleteOne({req.params.listId}, function(err, list){
if(err){res.json(err);};
else
{res.json({list: 'List successfully deleted'});}
};
});
UPDATE:
Upon running 'npm install cors --save', it was stored in my package.json .
server/package.json:
{
"name": "api",
"version": "1.0.0",
"description": ":)",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [
":)"
],
"license": "ISC",
"devDependencies": {
"nodemon": "^1.17.1"
},
"dependencies": {
"cors": "^2.8.4",
"express": "^4.16.2",
"mongoose": "^5.0.8",
"npm": "^5.7.1"
}
}
UPDATE:
I tried the following too:
ObjectID = require('mongodb').ObjectID;
exports.delete_a_list = function(req, res){
// console.log(req.params);
List.deleteOne({
_id: ObjectID(req.params.listId)}, function(err, list){
if(err)
res.json(err);
res.json({list: 'List successfully deleted'});
});
};'
This returns the same error including:
xhr.js?ec6c:178 OPTIONS http://localhost:3000/lists/undefined 404 (Not Found)
dispatchXhrRequest # xhr.js?ec6c:178
xhrAdapter # xhr.js?ec6c:12
dispatchRequest # dispatchRequest.js?c4bb:59
Promise.then (async)
request # Axios.js?5e65:51
Axios.(anonymous function) # Axios.js?5e65:61
wrap # bind.js?24ff:9
deleteList # GetList.vue?c877:131
boundFn # vue.esm.js?efeb:190
click # GetList.vue?d584:124
invoker # vue.esm.js?efeb:2004
fn._withTask.fn._withTask # vue.esm.js?efeb:1802
:1 Failed to load http://localhost:3000/lists/undefined: Response for preflight has invalid HTTP status code 404.
createError.js?16d0:16 Uncaught (in promise) Error: Network Error
at createError (createError.js?16d0:16)
at XMLHttpRequest.handleError (xhr.js?ec6c:87)
Thank you guys for all your suggestions.
I found the following video: https://www.youtube.com/watch?v=NEFfbK323Ok, from The Net Ninja, and was able to get it to finally work upon changing my code to reflect his particular method:
listRoutes.js:
app.route('/lists/:_id')
.get(lists.read_a_list)
// .update(lists.update_a_list)
.delete(lists.delete_a_list);
listController.js:
exports.delete_a_list = function(req, res){
// console.log(req.params);
List.findByIdAndRemove({_id: req.params._id}).then(function(list){
res.send(list);
});
};
GetList.vue:
deleteList : function(_id, List){
axios.delete('http://localhost:3000/lists/'+_id, List)
.then(response => {
this.List.splice(index, 1);
//refreshes Application
// window.location.reload();
})
}
Your problem ist related to CORS (cross-origin-resource-sharing).
If you are using node with express then just include this middleware:
https://www.npmjs.com/package/cors
This query seems wrong:
List.deleteOne({req.params.listId}, ...
Can you try modifying it like this?:
List.deleteOne({_id: ObjectID(req.params.listId}), ...
(You need to have ObjectID declared somewhere up: ObjectID = require('mongodb').ObjectID)

Cloud Foundry MongoDB Error ECONNREFUSED

I would like to deploy a Node.JS app on Cloud Foundry.
I follow the following steps:
Add the engines part in the package.json
{
"name": "vsapc",
"version": "1.0.0",
"description": "Application Name",
"main": "server/app.js",
"scripts": {
"start": "node server/app.js",
"backup": "node backup.js",
"restore": "node restore.js",
"seed": "node server/seed/Seed.js",
"postinstall": "node install.js"
},
"directories": {
"test": "test"
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.15.2",
"cfenv": "^1.0.3",
"express": "^4.14.0",
"jsonwebtoken": "^7.1.9",
"mongodb": "^2.2.5",
"mongoose": "^4.6.3",
"mongoose-seed": "^0.3.1",
"morgan": "^1.7.0",
"promise": "^7.1.1",
"prompt": "^1.0.0",
"winston": "^2.2.0",
"winston-daily-rotate-file": "^1.4.0"
},
"engines": {
"node": "6.11.*",
"npm": "5.*"
},
"author": "",
"license": "ISC"
}
I create the manifest.yml
---
applications:
- name: Policy_Studio
memory: 2048MB
env:
NODE_ENV: production
I used the following to connect in install.js:
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
let mongoUrl = '';
mongoUrl = vcapServices.mongodb[0].credentials.uri;
mongoose.connect(mongoUrl,{useMongoClient: true}, function (err){
if (err) {
console.log("Database connection responded with: " + err.message);
console.log("Is your server.config.json up to date?");
process.exit(1);
return
}
console.log("Connected to database.");
and the following in app.js:
Server.prototype.connectDatabase = function (url) {
mongoose.Promise = Promise;
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
let mongoUrl = '';
mongoUrl = vcapServices.mongodb[0].credentials.uri;
mongoose.connect(mongoUrl,{useMongoClient: true});
mongoose.connection.on("error", function (err) {
log.error(err)
});
mongoose.connection.once("openUri", function () {
log.info("Connected to DB")
})
};
connect by command line to SCAPP and push the app with cf push
As i don't have the MongoDB on the cloud i have an error
I build a MOngoDB service on the cloud and bind directly the app through the web GUI
On the gui i click restage button for my app
I have the error
Database connection responded with: failed to connect to server
[2xtorvw9ys7tg9pc.service.consul:49642] on first connect [MongoError:
connect ECONNREFUSED 10.98.250.54:49642]
I add the service mongoDB in my manifest and cf push my application
Still the same error as in point 9
I tried to change the connection in install.js
Thank you for your help
While your parsing of VCAP_SERVICES appears to work (you get a URL containing a hostname & port), i highly recommend to leverage one of the existing libraries for it for further projects:
https://www.npmjs.com/package/cfenv
Still, please that the parsing of your mongo credentials is properly working (cf e ${app_name}, look for VCAP_SERVICES, manually compare)
If you want to test your service with independent code, here is a sample app i quickly threw together to test all mongodb services bound to it:
package.json:
{
"name": "mongo-tester",
"version": "1.0.0",
"description": "tests all mongodbs via VCAP_SERVICES",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Michael Erne",
"license": "MIT",
"dependencies": {
"async": "^2.5.0",
"cfenv": "^1.0.4",
"lodash": "^4.17.4",
"mongodb": "^2.2.31"
}
}
server.js:
var cfenv = require('cfenv'),
_ = require('lodash'),
http = require('http'),
async = require('async'),
MongoClient = require('mongodb').MongoClient
var appEnv = cfenv.getAppEnv();
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Return something for CF Health Check\n');
}).listen(appEnv.port);
var services = _.values(appEnv.getServices());
var mongodbs = _.filter(services, { label: 'mongodb' });
async.eachLimit(mongodbs, 1, function (m, callback) {
MongoClient.connect(m.credentials.database_uri, function (err, db) {
if (err) {
return callback(err);
}
db.collection("debug").insertOne({"test": true}, function(err, res) {
if (err) return callback(err);
console.log("document inserted successfully into " + m.credentials.database_uri);
db.close();
return callback(null);
});
});
}, function (err) {
if (err) {
console.log(err.stack || err);
console.log('---> mongodb connection failed <---');
return;
}
console.log('---> connection to all BOUND mongodb successful <---');
});
It should print something like the following in its logs if it can connect to any of the bound mongodb services:
document inserted successfully into mongodb://xxx:yyy#zzz.service.consul:1337/databaseName
---> connection to all BOUND mongodb successful <---
If this fails with similar errors, the service instance seems broken (wrong url/port being reported). I would just recreate the service instance in that case and try again.
Finally we have found the problem. The cloud foundry is not allowing to access the MongoDB service during the postinstall phase. So we changed it to prestart and it worked.
Thank you for your help

Personality insight input var nodejs

var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<username>',
password: '<password>'
});
personality_insights.profile({
text: '<?php echo $_Session['description'];?>',
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
It doesn't display anything. I have also done npm watson cloud and saved it, I have put my credentials and also forked it on git. What am I missing? I am a beginner but would love to use this on my page!
Here are the steps to run it locally, since you are a beginner I'll start from the beginning.
Create a new folder and name it whatever you want. Put these files in there.
Name the first file: index.js
fill in <YOUR-USERNAME>, <YOUR-PASSWORD>, and <YOUR-100-UNIQUE-WORDS> variables.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var cfenv = require("cfenv");
var appEnv = cfenv.getAppEnv();
http.listen(appEnv.port, appEnv.bind);
var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<YOUR-USERNAME>',
password: '<YOUR-PASSWORD>'
});
personality_insights.profile({
text: "<YOUR-100-UNIQUE-WORDS>",
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
Create another file and name it: package.json
put these contents in there
{
"name": "myWatsonApp",
"version": "1.0.0",
"description": "A Watson Personality Insights application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"cfenv": "^1.0.3",
"express": "^4.13.4",
"watson-developer-cloud": "^2.2.0"
}
}
open your terminal and cd to the root of your folder you just created.
Run the command: npm install
Then run the command npm start
Your application will then be running and you will see output from the personality insights call you made in index.js

Resources