firstly sorry for my english, secondly I have a question about use of SOAP in Node.js. I am a beginner with node.js and I need help. This is my function:
var soap = require('soap');
var url = 'http://SOMETHING?wsdl';
var args = {
accountId: 'xxxxx',
userName: 'xxxxx',
password: 'xxxxxx',
targetNSAlias: 'tns',
targetNamespace: 'http://api.ilient.com/'
};
soap.createClient(url, function(err, client) {
if(err) throw err;
client.login(args,function(err, result, raw, soapHeader){
if(err) throw err;
console.log(result);
});
});
when I run I get this error:
Error: Cannot parse response
at /root/node_modules/soap/lib/client.js:321:21
at Request._callback (/root/node_modules/soap/lib/http.js:117:5)
at Request.self.callback (/root/node_modules/request/request.js:186:22)
at Request.emit (events.js:98:17)
at Request.<anonymous> (/root/node_modules/request/request.js:1081:10)
at Request.emit (events.js:95:17)
at IncomingMessage.<anonymous> (/root/node_modules/request/request.js:1001:12)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:944:16
someone can help me solve it?
Thanks and sorry for my english again.
I faced a similar problem. Maybe the SOAP web service that you are trying to consume has v1.2 specification and it might expect the content type as application/soap+xml instead of text/xml. In order to force node-soap to use SOAP 1.2 version you could add forceSoap12Headers: true among createClient() parameters.
On a side note, I had to add the ws-addressing headers to soap header because of The message with To ' ' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher error.
I edited your code as follows:
var soap = require('soap');
var url = 'http://SOMETHING?wsdl';
var args = {
accountId: 'xxxxx',
userName: 'xxxxx',
password: 'xxxxxx',
targetNSAlias: 'tns',
targetNamespace: 'http://api.ilient.com/'
};
var soapOptions = {
forceSoap12Headers: true
};
var soapHeaders = {
'wsa:Action': 'http://tempuri.org/MyPortName/MyAction',
'wsa:To': 'http://SOMETHING.svc'
};
soap.createClient(url, soapOptions, function(err, client) {
if(err) throw err;
client.addSoapHeader(soapHeaders, '', 'wsa', 'http://www.w3.org/2005/08/addressing');
client.login(args, function(err, result, raw){
if(err) throw err;
console.log(result);
});
});
Add this code: client.setSecurity(new soap.BasicAuthSecurity('username', 'password')); after your create client code. It worked for me:
var soap = require('soap');
var url = 'http://SOMETHING?wsdl';
soap.createClient(url, function(err, client) {
if(err) throw err;
client.setSecurity(new soap.BasicAuthSecurity('username', 'password'));
client.login(args, function(err, result) {
if(err) throw err;
console.log(result);
});
});
Related
I am trying to do a simple query to my azure SQL server from NodeJs, im getting errors that i cannot connect to the server. all the details are correct because i used them on another application i built in C#.
my code:
var mysql = require('mysql');
var config =
{
host: Server,
user: UserName,
password: PassWord,
database: Database
};
const conn = new mysql.createConnection(config);
conn.connect(
function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:");
throw err;
}
else
{
console.log("Connection established.");
queryDatabase();
}
});
function queryDatabase(){
conn.query('SELECT * FROM Drinks', function (err, results, fields)
{
if (err) throw err;
console.log(results);
})
conn.end(function (err) {
if (err) throw err;
else console.log('Done.')
});
};
I have tried making port rules, allowing nodejs through firewall, turning off firewall, I have added my IP to the firewall on the azure group and still cant connect. Any help would be awesome. Thanks!
Error:
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
--------------------
at Protocol._enqueue (C:\node\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\node\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\node\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\node\test.js:14:6)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
Ok so i worked out how to do it! and for anyone with similar issues do this.
Instead of mysql i used mssql and it worked straight away.
Example:
var sql = require('mssql');
var config = {
server: "XXX.database.windows.net",
database: "XXX",
user: "XXX",
password: "XXX",
port: 1433,
options: {
encrypt: true
}
};
sql.connect(config).then(function() {
console.log("connected")
sql.query('SELECT * FROM Drinks', function (err, results, fields)
{
if (err) throw err;
console.log(results);
})
})
I just started Backend in Node.js
Now i want to write a REST api in Node.js that is supposed to send Data into a Mysql Database. The GET request works fine apparently, so there are no Issues whatsoever with the GET Request, just the POST, which does not save information into the Database.
My Code is Looking Like this
app.post('/users/', function(req,res){
let sql ="insert into personal_info (name, email, gender, national_id,salary) values (?)";
let values = [req.body.name, req.body.email, req.body.gender,req.body.national_id,req.body.salary];
db.query(sql, [values], function(err, data, fields){
if (err) throw err;
res.json({
status: 200,
message: "New user added successfully"
})
});
});
Running it inside POSTman i am getting this :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /users</pre>
</body>
</html>
Is there something i appear to be Missing? Like I said, I am very new to this, and I do need clarification of some sort.
Edits
Code Looks Like this Now :
app.post('/api/user/', function(req,res){
let sql ="insert into personal_info (name, email, gender, national_id,salary) values (?,?,?,?,?)";
let values = [req.body.name, req.body.email, req.body.gender,req.body.national_id,req.body.salary];
dbcon.query(sql, [values], function(err, data, fields){
if (err) throw err;
res.json({
status: 200,
message: "New user added successfully"
})
});
});
And here is the Error
D:\Node_JSREST\nodejsrest_example>node index.js
Node app is on port 5900
D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?,?,?)' at line 1
at Query.Sequence._packetToError (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:189:13)
at addChunk (_stream_readable.js:284:12)
--------------------
at Protocol._enqueue (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\Connection.js:198:25)
at D:\Node_JSREST\nodejsrest_example\index.js:42:9
at Layer.handle [as handle_request] (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\layer.js:95:5)
at D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\index.js:335:12)
at next (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\index.js:275:10)
D:\Node_JSREST\nodejsrest_example>
Edits Again
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/',function(req,res){
return res.send({error:true, message : 'hello world'});
});
var dbcon = mysql.createConnection({host:'localhost',user:'root',password:'',database:'staffdb' });
dbcon.connect();
app.get('/users',function(req,res){
dbcon.query('select * from personal_info', function (error, results, fields){
if (error) throw error;
return res.send({ error: false, data: results, message: 'users list.' });
});
});
app.get('/users/:id',function (req, res){
let user_id = req.params.id;
if (!user_id) {
return res.status(400).send({ error: true, message: 'Please provide user_id' });
}
dbcon.query('select * from personal_info where id=?',user_id,function(error, results,fields){
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'users list.' });
});
});
app.post('/api/user/', function(req,res){
let sql ="insert into personal_info (name, email, gender, national_id,salary) values (?)";
let values = [req.body.name, req.body.email, req.body.gender,req.body.national_id,req.body.salary];
dbcon.query(sql, [values], function(err, data, fields){
if (error) throw error;
res.json({
status: 200,
message: "New user added successfully"
})
});
});
app.listen(5900,function(){
console.log('Node app is on port 5900');
});
module.exports = app;
I think your using the wrong node module for your database engine. Here you import the mysql:
var mysql = require('mysql');
But in the error we can see that you have an error for a mariaDB server:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?,?,?)' at line 1
I suggest you to try with the mariadb node module. Here is an example from mariadb.com. The README is also good.
today I tried node.js mysql snippet from w3schools:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "roots", // WRONG USER
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I wanted to learn how to handle mysql errors, because my app require mysql. But after I started app.js file this error showed up:
Why can't I throw an error?
I wanted to learn how to handle mysql errors, because my app require
mysql.
MySQLJS Error handling
To catch the errors you throw, try with the following snippet :
con.on('error', function(err) {
console.log("[mysql error]",err);
});
change you're database conn like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
I have nodejs app in Ejs framework , I'am a newbie to java script,
I need to know what is the correct way to set flash messages in Node.js
My Code given below throws me an error ,like this :
C:\Users\sad\Desktop\Node Application\routes\users.js:57
req.flash('error_mesg', 'A User with this name already exisit !!')
^
TypeError: Cannot read property 'flash' of null
at Request._callback (C:\Users\as\Desktop\Node Application\routes\users.js:57:10)
at Request.self.callback (C:\Users\sa\Desktop\Node Application\node_modules\request\request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1091:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Here goes my code where I initiate everything :
var flash = require('connect-flash');
// Global VArs
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
And here goes my Code where I really apply it :
var errors = req.validationErrors();
if(errors){
res.render('register' ,{
errors:errors
})
}else{
var newUser = {first_name,last_name, role,email,password,company,role}
request({
url: "http://127.0.0.1:8000/v1/dashboard/register/",
method: "POST",
json: true, // <--Very important!!!
body: newUser
}, function (req, res, err, body){
var status = res['statusCode']
console.log(typeof(status));
if (status = '400'){
req.flash('error_mesg', 'A User with this name already exisit !!')
}
});
}
There some related answers to this type of question but not specifically flash messages .
Here goes my html :{{#if error_msg}}
<div class="alert alert-danger">{{error_msg}}</div>
{{/if}}
Assuming the last bit of code you posted is the body of an express endpoint, I'm guessing you overwrote your express callback variables req and res in your callback to request. Also, that is not the current function signature for the request library callback, it should be function (error, response, body), not function (req, res, err, body). Fix the function signature, use unique variable names and it should work:
var errors = req.validationErrors();
if(errors){
res.render('register' ,{
errors:errors
})
}else{
var newUser = {first_name,last_name, role,email,password,company,role}
request({
url: "http://127.0.0.1:8000/v1/dashboard/register/",
method: "POST",
json: true, // <--Very important!!!
body: newUser
}, function (error, response, body){
var status = response.statusCode;
console.log(typeof(status));
if (status = '400'){
req.flash('error_mesg', 'A User with this name already exisit !!')
});
}
I'm using node-soap to communicate with web services, but i can't get it to work.
The code as it is below throws the error ECONNREFUSED. But if i don't put the args variable in the function I get a response. Does anyone know what can it be?
var soap = require('soap');
var wsdl, url;
var args = {cargoSn: 'MSWU0031179'};
soap.createClient(url, function(err, client) {
//console.log('client');
console.log(client.describe().TransportWebService.TransportWebServiceSoap.GetContainerPosition);
client.GetContainerPosition(args, function(err, result) {
console.log('err');
console.log(err);
console.log('result');
console.log(result);
}, {
proxy: "http://127.0.0.1:8888",
strictSSL: false
});
console.log(client.lastRequest);
}, url);
This is what i get when running the code from above:
err
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
result
undefined
And this is what I get when calling it without arguments:
client.GetContainerPosition(function(err, result) { ...
err
null
result
{ GetContainerPositionResult: '{"Status":"ERROR","Description":"Nothing found with serial number: ","Data":null}' }
So, it works when no arguments are passed (and obviously finds nothing), but gives an error when they are.