I need to connect Vue.js app to the remote MSSQL server.
I am using node.js, mssql library.
After setting up I get error.
How to make configuration settings in order to connect to mssql?
How to solve issues related to installation of libraries?
ERROR Failed to compile with 5 errors 1:39:06 PM
These dependencies were not found:
* dgram in ./node_modules/native-dns-cache/lookup.js, ./node_modules/native-dns/lib/server.js and 2 others
* fs in ./node_modules/native-dns/lib/platform.js
To install them, you can run: npm install --save dgram fs
package.json dependencies:
...
},
"dependencies": {
"dgram": "^1.0.1",
"dns": "^0.2.2",
"firebase": "^4.10.0",
"fs": "0.0.1-security",
"highcharts": "^6.0.7",
"mssql": "^4.1.0",
"net": "^1.0.2",
"tls": "0.0.1",
"vue": "^2.5.3",
"vue-highcharts": "0.0.10",
"vue-router": "^3.0.1",
"vuetify": "^0.17.7",
"vuex": "^3.0.1"
}, ...
I solve this problem. As I am very new in this environment. Vue app renders client-side. I build server-side using template "webpack-ssr".
Here is more information about server-side rendering
here is my test code:
...
const sql = require('mssql')
...
// Create connection to database
const databaseConfig = {
userName: 'USER_NAME',
password: 'PASSWORD',
server: 'SERVER_NAMECLOUDAPP.AZURE.COM',
database: 'DATABASE',
options: {
encrypt: true // Use this if you're on Windows Azure
}
}
...
Data conncetion:
// mssql connect for database
sql.connect(databaseConfig, err => {
// ... error checks
if (err) {
console.log('error: ' + err)
} else {
console.log('conencted')
}
// Query
new sql.Request().query('select 1 as number', (err , result) => {
// ... error checks
...
console.dir(result + ' hmmm ... not good')
})
})
...
Related
I'm using the mssql package for node in a MacOs Monterey:
import mssql from "mssql"
connect = async () => {
try {
var cfg = {
server: "10.0.0.180",
authentication: {
type: "default",
options: {
userName: "username",
password: "password",
},
},
options: {
encrypt: true,
enableArithAbort: true,
integratedSecurity: true,
trustServerCertificate: true,
rowCollectionOnDone: true,
database: "db",
cryptoCredentialsDetails: {
// Required for SQL Server 2012 connection,
// as node 18 uses a newer TLS protocol
minVersion: "TLSv1",
},
},
};
let conn = await mssql.connect(cfg);
return conn;
} catch (error) {
return null;
}
return false;
};
Working with node v18.13.0 I'm getting the following error:
ConnectionError: Failed to connect to 10.0.0.180:1433 - 0036761901000000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:../deps/openssl/openssl/ssl/statem/statem_lib.c:1986:
My project config:
"dependencies": {
"mssql": "^9.0.1",
"nconf": "^0.12.0",
"qs": "^6.11.0"
},
"devDependencies": {
"#babel/core": "^7.20.2",
"#babel/node": "^7.20.2",
"#babel/preset-env": "^7.20.2",
"babel-loader": "^9.1.0",
"webpack": "^5.75.0",
"webpack-cli": "^4.10.0"
}
I'm stuck on that as I cannot connect to the database. What might be causing this?
So I'm working on a Nodejs project with expressjs and I'm trying to use Jest to test my apis.
I've read about configuring Jest in the documentation, but I'm new to jest and it's a bit confusing.
The error I'm getting :
SyntaxError: Cannot use import statement outside a module at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
My test file:
const userController = require("../controllers/user.controller");
const router = require("../routes/user.routes");
//Testing login route
describe("POST /api/user/login", () => {
describe("given a username and password", () => {
test("should respond with a 200 status code", async () => {
const response = await request(router).post("/login").send({
username: "username",
password: "password"
})
expect(response.statusCode).toBe(200)
})
})
})
I had to install babel-jest
"devDependencies": {
"#babel/core": "^7.18.6",
"#babel/preset-env": "^7.18.6",
"babel-jest": "^28.1.2",
"jest": "^28.1.2",
"supertest": "^6.2.4"
}
and added a file called .babelrc to my project containing this code:
{
"presets": [
"#babel/preset-env"
]
}
I'm over a month into development of a MEVN app with MySQL. I'm using a framework called MEVN-CLI but that shouldn't really matter.
I keep having to change my server port ever few days whenever I get this error:
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,html,css,json,md
[nodemon] starting `node run server.js --port 9000/api --open`
events.js:288
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1309:16)
at listenInCluster (net.js:1357:12)
at Server.listen (net.js:1445:7)
at Function.listen (C:\Dev\Projects\node-mysql\server\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Dev\Projects\node-mysql\server\server.js:258:5)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1336:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 3000
}
I change between 9000, 3000, 3002, 8000, etc. I want to keep it on a single port but this keeps happening and I can't find what's causing it.
I have a client and a server, they communicate with Axios, my Server communicates with a MySQL server I host elsewhere but I also think this is irrelevant but I figure it can't hurt to share that.
Here is my server:
const port = process.env.PORT || 4000;
const env = require("./env.json");
const express = require("express");
const mysql = require("mysql");
const path = require("path");
const bodyParser = require("body-parser");
const favicon = require("serve-favicon");
const app = express();
const cors = require("cors");
const {
testColumns,
showUsers,
searchResultColumns,
showAccountColumns
} = require("./mysql/columns");
app.use(bodyParser.json());
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(cors());
//* Build MySQL Connection
const db = mysql.createConnection({
host: env.server,
user: env.user,
password: env.pass,
database: env.schema
});
//* Connect to Database
db.connect((err) => {
if (err) {
console.log("Error Connecting:", err);
}
console.log("MySQL Connected...");
});
app.get(`/api/v1/:query/:x`, (req, res) => {
[Business Logic - Works fine]
if (err) {
// If error
console.log(err);
}
// If no results
else if (results == 0) {
res.send(`No Results\n ${results} \n - ${err}`);
return;
}
// If successful
res.send(results);
});
});
app.get(`/api/v1/:query/`, (req, res) => {
[Business Logic - Works fine]
if (err) {
// If error
console.log(err);
}
// If no results
else if (results == 0) {
res.send(`No Results\n ${results} \n - ${err}`);
return;
}
// If successful
res.send(results);
});
});
//* Root Handler
app.get("/", (req, res) =>
res.sendFile(path.join(__dirname + "/public/index.html"))
);
//? Error Handler
app.get("/404", (req, res) =>
res.sendFile(path.join(__dirname + "/public/404.html"))
);
//! Error Handler
app.get("/sample", (req, res) =>
res.sendFile(path.join(__dirname + "/public/sample.html"))
);
//? Listen for server port
app.listen(port, () => {
console.log(`Sample Dev Server at:${port}`);
});
I deleted some stuff that's not really relevant because it was hundreds of similar lines, I haven't abstracted my routing away yet.
This is my router:
import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import NotFound from "./views/NotFound.vue";
Vue.use(Router);
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/NotFound",
name: NotFound,
component: () => import("./views/NotFound.vue")
},
{
path: "/search",
component: searchPage,
children: [
{ path: "/search/byName", component: searchByName },
{ path: "/search/china", component: searchByNumber }
]
}
]
});
And if it's relevant, this is my packages.json file:
{
"name": "vmax",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.19.2",
"core-js": "^3.6.4",
"vue": "^2.6.11",
"vue-router": "^3.1.6",
"vuetify": "^2.2.11"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.3.0",
"#vue/cli-plugin-eslint": "~4.3.0",
"#vue/cli-service": "~4.3.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"sass": "^1.19.0",
"sass-loader": "^8.0.0",
"vue-cli-plugin-vuetify": "~2.0.5",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.3.0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
I changed just now to port 4000 and it's working just find but something is wrong that's causing me to have to change server ports every few days.
Probably the PORT is in use.
To terminate program PORT,
$ killall -9 node
Node / Express: EADDRINUSE, Address already in use happens when closing VS Code, particularly on Windows when a server is running with WSL.
I'm currently using something called CurrPorts which is free to view which ports are in use, and force close them.
To be clear, it's not specific to Windows or WSL, but that is where it seems most prevalent. If you're in the habit of using port 3000, 5500, or 8080 for example - it's likely in use by Node.
Add this in your "package.json" file
"stop-win": "Taskkill /IM node.exe /F",
"stop-linux": "killall node"
For my internship I am making a chatbot. I created a bot using botkit framework (yo botkit) and got as far as using it in the ms Teams client. But only using my localhost + ngrok setup. when I want to use https://{myproject}.azurewebsites.net/api/messages after deployment I get a 502 error message.
To try if I actually did my deployment okay, I made another project using "yo botbuilder" without botkit framework. Following the same steps I deployed it to a fresh Group. This time using the https://{myproject}.azurewebsites.net/api/messages url worked. (standard echo bot)
After that, I copied my bot files from my first project into my new one and replaced my index.js from my standard botbuilder project with my bot.js file from my botkit framework project.
I just used the standard botbuilder -> index.js file and botkit -> bot.js file +
in my package.json I changed the main and the scripts to point to bot.js instead of index.js.
After deploying, it just gave me my 502 again.
index.js
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');
// This bot's main dialog.
const { EchoBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError] unhandled error: ${ error }`);
// Send a trace activity, which will be displayed in Bot Framework Emulator
await context.sendTraceActivity(
'OnTurnError Trace',
`${ error }`,
'https://www.botframework.com/schemas/error',
'TurnError'
);
// Send a message to the user
await context.sendActivity('The bot encountered an error or bug.');
await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};
// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;
// Create the main dialog.
const myBot = new EchoBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
// Listen for Upgrade requests for Streaming.
server.on('upgrade', (req, socket, head) => {
// Create an adapter scoped to this WebSocket connection to allow storing session data.
const streamingAdapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Set onTurnError for the BotFrameworkAdapter created for each connection.
streamingAdapter.onTurnError = onTurnErrorHandler;
streamingAdapter.useWebSocket(req, socket, head, async (context) => {
// After connecting via WebSocket, run this logic for every request sent over
// the WebSocket connection.
await myBot.run(context);
});
});
bot.js
const { Botkit } = require('botkit');
const { BotkitCMSHelper } = require('botkit-plugin-cms');
// Import a platform-specific adapter for botframework.
const { MongoDbStorage } = require('botbuilder-storage-mongodb');
// Load process.env values from .env file
require('dotenv').config();
let storage = null;
if (process.env.MONGO_URI) {
storage = mongoStorage = new MongoDbStorage({
url : process.env.MONGO_URI,
});
}
const controller = new Botkit({
webhook_uri: '/api/messages',
adapterConfig: {
appId: process.env.APP_ID,
appPassword: process.env.APP_PASSWORD,
},
storage
});
if (process.env.CMS_URI) {
controller.usePlugin(new BotkitCMSHelper({
uri: process.env.CMS_URI,
token: process.env.CMS_TOKEN,
}));
}
// Once the bot has booted up its internal services, you can use them to do stuff.
controller.ready(() => {
// load traditional developer-created local custom feature modules
controller.loadModules(__dirname + '/features');
/* catch-all that uses the CMS to trigger dialogs */
if (controller.plugins.cms) {
controller.on('message,direct_message', async (bot, message) => {
let results = false;
results = await controller.plugins.cms.testTrigger(bot, message);
if (results !== false) {
// do not continue middleware!
return false;
}
});
}
});
controller.webserver.get('/', (req, res) => {
res.send(`This app is running Botkit ${ controller.version }.`);
});
package.json
{
"name": "my-chat-bot",
"version": "1.0.0",
"description": "Demonstrate the core capabilities of the Microsoft Bot Framework",
"author": "Generated using Microsoft Bot Builder Yeoman generator v4.7.0",
"license": "MIT",
"main": "bot.js",
"scripts": {
"start": "node ./bot.js",
"watch": "nodemon ./bot.js",
"lint": "eslint .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com"
},
"dependencies": {
"botbuilder": "~4.7.0",
"dotenv": "^8.2.0",
"restify": "~8.4.0",
"botbuilder-storage-mongodb": "^0.9.5",
"botkit": "^4.6.2",
"botkit-plugin-cms": "^1.0.3",
"firebase-admin": "^8.9.2",
"jira-client": "^6.15.0",
"request": "^2.88.2"
},
"devDependencies": {
"eslint": "^6.6.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"nodemon": "~1.19.4"
}
}
I'm trying to make a GET API request in my first react-native app(expo project, running it on my physical android device).
I'm seeing trouble while trying to make a get request using Axios - I have my backend in express connecting to Firebase DB.
{The below setup works fine in react web app}
...
const handleSubmit = () => {
const userData = {
email: email,
password: password
};
axios.get('/alltests')
.then((res) => {
alert("Successfully loggedin", res)
console.log(JSON.stringify(res.data))
})
.catch((err) => {
console.log("\n\nI'm in error block - frontend")
console.log(err)
alert(err);
//setErrors(err.response.data)
})
...
My package.json looks like ->
"dependencies": {
"#material-ui/core": "^4.8.1",
"#material-ui/icons": "^4.5.1",
"axios": "^0.19.0",
"cors": "^2.8.5",
"expo": "~36.0.0",
"react": "~16.9.0",
"react-dom": "~16.9.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz",
"react-native-paper": "^3.4.0",
"react-native-vector-icons": "^6.6.0",
"react-native-web": "~0.11.7"
},
"devDependencies": {
"babel-preset-expo": "~8.0.0",
"#babel/core": "^7.0.0"
},
"private": true,
"proxy": "https://asia-something.net/api"
}
However, if I use
axios.get('https://asia-something.net/api/alltests')
this seems to be working in the code.
I'm not using localhost or running the backend on local server.
Can someone help me here, please?