Node-red "no response object" - node.js

I'm trying to create a http get node that takes form data and then creates an http post to another web site using a rest API. I'm able to get the http call to return the correct payload however the http response node is giving a "no response object" error in the debug tab and the client never returns. Do I specifically need to do something to pass the response object so the call sends the correct response object to the http response node?
Here is the flow:
[{"id":"7011e7a9.8fee18","type":"http request","name":"","method":"use","ret":"obj","url":"","x":499,"y":84,"z":"51693a88.ae96c4","wires":[["efea497c.1015b8"]]},{"id":"589f2a18.a760d4","type":"function","name":"","func":"var myprocess = context.global.process;\nmyprocess.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\";\nvar dev_url = \"https://website.com:22411/central/api/qracore/browses?browseId=mfg:gp239\";\n \nvar msg = {\n \"method\" : \"GET\",\n \"url\" : dev_url,\n \"headers\" : {\n \"Authorization\": \"Basic abWZnQHFhZC5jb206=\",\n \"Origin\" : \"mybox.com\"\n }\n};\n \nreturn msg;","outputs":1,"noerr":0,"x":323,"y":154,"z":"51693a88.ae96c4","wires":[["7011e7a9.8fee18"]]},{"id":"9f65b624.609a48","type":"debug","name":"","active":true,"console":"false","complete":"payload","x":810,"y":211,"z":"51693a88.ae96c4","wires":[]},{"id":"38e4c04d.c71b4","type":"http in","name":"","url":"/workOrders","method":"get","swaggerDoc":"","x":152,"y":190,"z":"51693a88.ae96c4","wires":[["589f2a18.a760d4"]]},{"id":"e5ee54b2.1a11a8","type":"http response","name":"","x":770,"y":96,"z":"51693a88.ae96c4","wires":[]},{"id":"efea497c.1015b8","type":"function","name":"","func":"var newMsg = { payload: msg.payload };\nreturn newMsg;","outputs":1,"noerr":0,"x":582,"y":214,"z":"51693a88.ae96c4","wires":[["e5ee54b2.1a11a8","9f65b624.609a48"]]}]

The key is to pass it from node to the other. You do that by using the req and the res from the msg to pass to the output.
var newMsg = { payload: msg.payload };
//return [msg, newMsg];
newMsg.user = msg.req.body["user"];
newMsg.req = msg.req;
newMsg.res = msg.res;
return newMsg;

Related

How to configure client for access with authsecret?

I'm using the client and I need to call a service using authsecret parameter.
If I ad this param to the base url it give me a serialization error.
String baseUrl = AppConfig.GetAppApiUrl();
var client = new JsonServiceClient(baseUrl.AddQueryParam("authsecret","secretz123!"));
var c = client.Send(new ComuneRequest { Id = "A001" });
Using Fiddler I discovered that the request that the client generate is incorrect:
POST
http://192.168.0.63:820/?authsecret=secretz123%21/json/reply/ComuneRequest
So, what I have to do to make the client create a request in a correct format?
It needs to be sent as a Request Parameter (i.e. QueryString or FormData) which you can do using HTTP Utils with:
var url = baseUrl.CombineWith(requestDto.ToUrl()).AddQueryParam("authsecret", secret);
var res = url.GetJsonFromUrl().FromJson<MyResponse>();
Otherwise since AuthSecret is not a property on your Request DTO you wont be able to send it as a Request Parameter in the Request Body, but you should be able to send the param in the Request Headers with:
var client = new JsonServiceClient(baseUrl) {
RequestFilter = req => req.Headers[HttpHeaders.XParamOverridePrefix+"authsecret"] = secret
};

Vertx client for sending get request with parameters

I am writing client in Vertx for sending get request with two string parameters but i am receiving empty list from server. If i write request to another service which is on the same path but this service is not receiving any parameters the response is ok and the data is properly returned. The problem is with mapping the parameter on server side with .addQueryParam the parameter is not mapped well on server side. any help?
WebClient client = WebClient.create(vertx);
client
.get(80, "localhost", "/mainpath/path1")
.addQueryParam("startDate", "1459926000")
.addQueryParam("endDate", "1459926900")
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
JsonArray body = response.bodyAsJsonArray();
System.out.println("Received response with status code " + response.statusCode() + " with body " + body.toString());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}

Use nlapiRequestURL to make a request to a Service

How do you use nlapiRequestURL to make a request to a service? My attempt below is failing with the error: UNEXPECTED_ERROR (output from NetSuites script execution log).
My service is set to run without login and works correctly when I directly access it through a browser using its url. Its just the request through nlapiRequestURL thats failing.
Any idea what could be going wrong?
// This code executes in Account.Model.js (register function)
// I am using my own netsuite user credential here
var cred = {
email: "MY_NETSUITE_EMAIL"
, account: "EXXXXX" // My account id
, role: "3" // Administrator
, password: "MY_NETSUITE_PASSWORD"
};
var headers = {"User-Agent-x": "SuiteScript-Call",
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
var payload = {
type: 'is_email_valid'
, email: 'spt015#foo.com'
};
// A raw request to the service works fine:
// http://mywebsite.com/services/foo.ss?type=is_email_valid&email=spt015#foo.com
// Error occurs on next line
var response = nlapiRequestURL(url, payload, headers);
You are attempting to call a non-Netsuite url with Netsuite authentication headers. You do not need that unless for some reason of your own you have implemented NS-style authorization on your service.
nlapiRequestURL does not automatically format a payload into a query string. If your service takes a posted JSON body then you need to call JSON.stringify(payload) e.g
var response = nlapiRequestURL(url, JSON.stringify(payload), headers);
If your service needs a query string like in your example then you need to construct a query string and append it to your service url. e.g.
var qs = '';
for(var k in payload) qs += k +'='+ uriEncodeComponent(payload[k]) +'&';
var response = nlapRequestURL(url +'?'+ qs.slice(0,-1), null, headers);
I would suggest changing your nlapiRequestURL to a GET instead of POST, and add the parameters to the url instead. Your function call will look like this instead.
nlapiRequestURL(url, null, headers, "GET")

I'm trying to send emails using sendgrid in nodejs.But am getting "TypeError: object is not a function" error

Here is my code snippet
var sendgrid = require('sendgrid')('xxxxxx', 'xxxxxx');
var email = new sendgrid.Email();
email.addTo('xyz#gmail.com');
email.setFrom('xyz#gmail.com');
email.setSubject('welcome to send grid');
email.setHtml('<html><body>HELLO evryone ...,</body></html>');
sendgrid.send(email, function(err, json) {
if(!err)
{
console.log("mail sent successssss");
res.send({"status":0,"msg":"failure","result":"Mail sent successfully"});
}
else
{
console.log("error while sending mail")
res.send({"status":1,"msg":"failure","result":"Error while sending mail."});
}
});
Installed sendgrid throgh npm also.am getting "TypeError: object is not a function" error.MAy i know why.??
Version:--
sendgrid#3.0.8 node_modules\sendgrid
└── sendgrid-rest#2.2.1
It looks like you're using sendgrid#3.0.8 but trying to call on the sendgrid#2.* api.
v2 implementation: https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/nodejs.html
v3 implementation:
https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/nodejs.html
Give the v3 a go.
As for the type error:
v2
var sendgrid = require("sendgrid")("SENDGRID_APIKEY");
you're invoking a function
however you have v3 installed
require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
and it's now an object
REQUESTED UPDATE:
I don't know too much about the keys given, but since they have tons of different supported libraries, it's completely possible that some of them use both while others use only one. If you really only have a USER_API_KEY nad PASSWORD_API_KEY, just use the user_api_key
Here is their source for the nodejs implementation module SendGrid:
function SendGrid (apiKey, host, globalHeaders) {
var Client = require('sendgrid-rest').Client
var globalRequest = JSON.parse(JSON.stringify(require('sendgrid-rest').emptyRequest));
globalRequest.host = host || "api.sendgrid.com";
globalRequest.headers['Authorization'] = 'Bearer '.concat(apiKey)
globalRequest.headers['User-Agent'] = 'sendgrid/' + package_json.version + ';nodejs'
globalRequest.headers['Accept'] = 'application/json'
if (globalHeaders) {
for (var obj in globalHeaders) {
for (var key in globalHeaders[obj] ) {
globalRequest.headers[key] = globalHeaders[obj][key]
}
}
}
The apiKey is attached to the header as an auth, and it looks like that's all you need.
Try following their install steps, without your own implementation,
1) (OPTIONAL) Update the development environment with your SENDGRID_API_KEY, for example:
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
========
2) Make this class and if you did the above use process.env.SENDGRID_API_KEY else put your USER_API_KEY
var helper = require('sendgrid').mail
from_email = new helper.Email("test#example.com")
to_email = new helper.Email("test#example.com")
subject = "Hello World from the SendGrid Node.js Library!"
content = new helper.Content("text/plain", "Hello, Email!")
mail = new helper.Mail(from_email, subject, to_email, content)
//process.env.SENDGRID_API_KEY if above is done
//else just use USER_API_KEY as is
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
var requestBody = mail.toJSON()
var request = sg.emptyRequest()
request.method = 'POST'
request.path = '/v3/mail/send'
request.body = requestBody
sg.API(request, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})

How to log the response message in a Registered Handler - ServiceStack RabbitMQ

Given this snippet of code:
//DirectApi
mqServer.RegisterHandler<LeadInformationInfo>(m =>
{
repository.SaveMessage(m as Message);
LeadInformationInfoResponse response = new LeadInformationInfoResponse();
try
{
var client = new JsonServiceClient(settingsFactory.GetMasterSetting("ProcessorApi:baseUri"));
response = client.Post(m.GetBody());
}
catch (WebServiceException webServiceException)
{
_log.Error("RegisterHandler<LeadInformationInfo>", webServiceException);
response = ((LeadInformationInfoResponse) webServiceException.ResponseDto);
response.CorrelationId = m.Id;
}
// Log response message here
return response;
}, 1);
I've gone to great lengths to make sure that a correlationId based off the original message Id property is propagated through the life of this message and any child messages spawned from this action. How do I get a handle on the response message so that I may log it in the handler? I only have access to the ResponseDto and not the message.
One of the reasons for this request is that the message queue client does not have access to the database, only the process that has the handler registered does. Hope that explains the situation better.
Just to clarify, this question is about persisting a MQ Response Message in the handler, the correlation Id is something that all messages in 1 request/response workflow will share. I'm also using ServiceStack ORMlite to persist the Message object, so querying this table by ID for troubleshooting is paramount.
Thank you,
Stephen
You're calling a WebService from within your MQ Handler:
var client = new JsonServiceClient(...);
response = client.Post(m.GetBody());
So there is no MQ Response which is only available in MQ Services. Although the WebService will return the response for the request that's sent so you can either use the CorrelationId on the MQ Request, otherwise you can have your Response DTO implement an interface like IHasCorrelationId and get it that way, e.g:
var correlationResponse = response as IHasCorrelationId;
if (correlationResponse != null)
{
var correlationId = correlationResponse.CorrelationId;
}
Create your own Instance of Message
As the Message<T> class is just a POCO if you wanted to create your own you can intialize your own instance:
var mqResponse = new Message<Response>(response);
If you only had the runtime late-bound type info, you can create one with:
var mqResponse = MessageFactory.Create(response);
Use RabbitMQ Message Filters
If you just wanted to log incoming and outgoing messages you can use the RabbitMQ Message Filters, e.g:
var mqServer = new RabbitMqServer("localhost")
{
PublishMessageFilter = (queueName, properties, msg) => {
properties.AppId = "app:{0}".Fmt(queueName);
},
GetMessageFilter = (queueName, basicMsg) => {
var props = basicMsg.BasicProperties;
receivedMsgType = props.Type; //automatically added by RabbitMqProducer
receivedMsgApp = props.AppId;
}
};

Resources