Java web application node integration issue - spring

I am having a web application which is sending a request to my node.js. Node module is calling my Spring REST module.
My web application to node call is as below
$.ajax({
type : "POST",
url : "http://localhost:9090/module",
dataType : 'json',
data : msgDetails,
xhrFields : { withCredentials : true },
success : function(data) {
console.log("getInbox" + JSON.stringify(data.message));
}, error : function(data) {
alert("Error in the AJAX response." + data);
} });
my node is as below
var express = require("express"),
app = express(),
http = require("http").createServer(app);
var requestObj = require('request');
responseBody = "";
indexresponseBody = null;
app.use(express.bodyParser());
app.post('/module', function(req, res){
var tempInbox = "";
var tmp = req;
var authKey = req.body.pubKey;
var reqBody = req.body;
console.log("POST"+" - "+JSON.stringify(reqBody)+" - "+authKey);
restCMCall("http://ip:port/restmodule/controller/call", req, res,authKey,reqBody);
//res.end(JSON.stringify(body));
res.header('Content-Type', 'application/json');
//resp.header('Charset', 'utf-8');
res.send({"name1":"name"});
});
function restCMCall(resturl, req, res, authKey,reqBody){
var i = 0;
console.log("reqBody :- "+reqBody+" resturl "+resturl+" "+i++);
requestObj({
url : resturl,
method : "POST",
headers : { "Content-Type" : "application/json","pubKey":authKey},
body : JSON.stringify(reqBody)
},
function (error, resp, body) {
tempInbox = body;
console.log(resp+" inbox body :- "+" -------- "+i++);
//resp.writeHead(200, {'Content-Type':'application/json','charset':'UTF-8'});
//res.write(JSON.stringify({"hello":"xxx"}));
//res.end(JSON.stringify(body));
res.header('Content-Type', 'application/json');
//resp.header('Charset', 'utf-8');
res.send(body);
}
);
console.log(i++);
}
Till now I am able to get the response from the spring module and is able to print on node console. But when I am trying to add this response in response of request made by web application then it is not sent.
In Firefox Browser firebug it shows as
Response Headers
Connection keep-alive
Content-Length 21
Content-Type application/json
Date Mon, 07 Oct 2013 16:13:38 GMT
X-Powered-By Express
but response tab as blank.
I am using express module to call spring rest web service calls node.js.
Please let me know if I am missing anything. I have also tried using
response.json(body)
But this is also not working.

I believe you should be making the request to url : "http://localhost:9090/getInbox" because you have not created an endpoint in your Node app that matches POST: /module

Related

Getting a 403 Forbidden error on plugin request

I'm trying to fire a plugin request from my ICN plugin. The request goes as below. However, I'm getting a 403 Forbidden error from the server.
Forbidden
You don't have permission to access /navigator/jaxrs/plugin on this server.
https://<icnserver.com>/navigator/jaxrs/plugin?repositoryId=Demo&query=%5B%7B%22name%22%3A%22ID%22%2C%22operator%22%3A%22LIKE%22%2C%22values%22%3A%5B%22123434234%22%2C%22%22%5D%7D%5D&className=Checks&plugin=DemoPlugin&action=DemoService&desktop=Demo
Plugin JS:
aspect.around(ecm.model.SearchTemplate.prototype, "_searchCompleted", function advisingFunction(original_searchCompleted){
return function(response, callback, teamspace){
var args = [];
var templateName = response.templates[0].template_name;
var res = response;
var requestParams = {};
requestParams.repositoryId = this.repository.id;
requestParams.query = query;
requestParams.className = templateName;
Request.invokePluginService("DemoPlugin", "DemoService",
{
requestParams: requestParams,
requestCompleteCallback: lang.hitch(this, function(resp) { // success
res.rows = resp.rows;
res.num_results = resp.rows.length;
res.totalCount = resp.rows.length;
args.push(res);
args.push(callback);
args.push(teamspace);
original_searchCompleted.apply(this,args);
})
}
);
}
});
You need to provide a security_token to be able to call your service, so you need to login first.
Then, open your browser's debug and check the requests in the network tab.
There you can see that every request that targets the /navigator/jaxrs/* URI will contain it, so something like this will be among the headers:
security_token: 163594541620199174
So my bet is that you have not set it in your client (I recommend a postman to test your service, or I would add a test (ICN) feature page in the ICN plugin project in order to be able to call it properly). In your feature page, you can call your service directly using the ecm/model/Request OOTB navigator dojo/javascript class, as you can see in CheckinAction.js:
_checkInDocument: function (item, requestData)
{
var self = this;
var payLoadObject = {requestType: "Get", id: item.id};
Request.postPluginService("DocuSignPlugin", "UpdateSignedDocumentService", "application/json", {
requestParams: {
repositoryId : item.repository.id,
serverType : item.repository.type,
docId : item.docid,
envelopeId: item.attributes.DSEnvelopeID,
payLoad: json.stringify(payLoadObject)
},
requestCompleteCallback: function(response) {
if (response.returncode == 0)
{
item.attributeDisplayValues.DSSignatureStatus = "Checkedin";
item.attributes.DSSignatureStatus = 4;
item.update(item);
}
else if (response.returncode == -1)
{
items = [];
items.push(item);
self._showLoginDialog(items);
}
},
backgroundRequest : false,
requestFailedCallback: function(errorResponse) {
// ignore handline failures
}
});
},
As you can see, you don't have to add the security_token to the requestParams, the framework will do it for you.

"405 (Method Not Allowed) and Response for preflight does not have HTTP ok status Error"

I'm building a simple web application and i'm making an XMLHttpRequest() POST request call to a URL that is hosted on Azure. I'm getting the following error:
"405 (Method Not Allowed)"
"Response for preflight does not have HTTP ok status Error"
I have also enabled my CORS extension on my browser. Below is my code:
var xhr = new XMLHttpRequest();
var url = "MyURL" // URL is Correct, I verified!
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log("Data is: " + json);
}
};
var obj = { SignId: getSignIdArr[temp] , BarCodeId: getBarCodeIdArr[temp],
BaseType: getBaseTypeArr[temp], Condition: getConditionArr[temp],
ConditionDate: getConditionDateArr[temp], Owner: getOwnerArr[temp],
Custodian: getCustodianArr[temp], FaceMaterial: getFaceMaterialArr[temp],
FacingDirection: getFacingDirectionArr[temp], Height: getHeightArr[temp],
Illuminated: getIlluminatedArr[temp], MountType: getMountTypeArr[temp],
Notes: getNotesArr[temp], Code: getCodeArr[temp],
Description: getDescriptionArr[temp], Dimensions: getDimensionsArr[temp],
Type: getTypeArr[temp], Status: getStatusArr[temp],
Support: getSupportArr[temp], RetroRefTextSymbol: getRetroRefTextSymbolArr[temp],
RetroRefBackground: getRetroRefBackgroundArr[temp],
RetroRefTestFailed: getRetroRefTestFailedArr[temp], MaterialCost: getMaterialCostArr[temp],
LabourCost: getLabourCostArr[temp], InstallationCost: getInstallationCostArr[temp],
ReflectiveCoating: getReflectiveCoatingArr[temp],
ReflectiveRating: getReflectiveRatingArr[temp],
OptimisticLockField: getOptimisticLockFieldArr[temp], GCRecord: getGCRecordArr[temp],
NewSupport: getNewSupportArr[temp], SignGroup: getSignGroupArr[temp],
RetroRefDate: getRetroRefDateArr[temp], EquipmentCost: getEquipmentCostArr[temp]
};
var data = JSON.stringify(obj);
xhr.send(data);
Any help will be greatly appreciated! Stuck in this for a while. Thanks all!

HttpClient Returns 404 not found

I have a xamarin app that pull data from a webAPI. I check api address so many times and i am sure it is correct. When i debug my code i have 404 not found error from server. However when i copy and paste the URL to browser i have expected result. I couldn't figure out why my app return 404.
My Method:
public async Task<ICustomerType> GetById(int id)
{
string _token;
if (App.Current.Properties.ContainsKey("token"))
{
_token = (string)App.Current.Properties["token"];
}
else
{ _token = null; }
var webApiResponse =
_connector.PostAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
var response = webApiResponse.Result.ToString();
var jObjectResponse = JObject.Parse(response);
ICustomerType customerTypeObj = null;
return customerTypeObj;
}
My bridge method to HttpClient's PostAsync method:
private async Task<TResponse> PostAsync(string requestPath, string
jsonContent, bool getToken, string token)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(_apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
if (getToken)
{
token = GetApiTokenAsync().Result;
}
if (!string.IsNullOrEmpty(token))
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
}
var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = client.PostAsync(requestPath, httpContent).Result;
var jsonData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResponse>(jsonData);
}
Token: Correct
API Url: Correct(I check "/" signs from debug output.They are well placed. My Api like:
https://MyApi.net/api/Personel/get/id/1)
My Error:
response {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Request-Context:
appId=cid-v1:Some_String Server: Kestrel
Strict-Transport-Security: max-age=Some_Int Set-Cookie:
ARRAffinity=Some_String;Path=/;HttpOnly;Domain=MyDomain Date: Mon,
09 Jul 2018 07:54:19 GMT X-Powered-By: ASP.NET Content-Length: 0
}} System.Net.Http.HttpResponseMessage
your method verb in API is "GET" but you used "POST" in the client So in browser works because browser call "GET", but in the client doesn't work.
instead of :
var webApiResponse =
_connector.PostAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
use :
var webApiResponse =
_connector.GetAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;

Slack WebAPI fails with not_authed

I'm attempting to post interactive messages to slack as a Bot User (using chat.postMessage, etc).
Although I am passing in the Bot Access Token (as received from the initial OAuth) I keep getting an error response stating "not_authed".
I get the same when I attempt auth.test.
I'm doing something like the following with "request" in node.js:
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
uri: slackMessageURL,
method: "POST",
token: bToken
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});
which results with:
auth.test response: {"statusCode":200,"body":"{\"ok\":false,\"error\":\"not_authed\"}",...
According to the Slack WebAPI docs, if I'm posting as the Bot, I should use the Bot's access token (as received from the initial oauth), but figure I'm either formatting my request incorrectly, or the token is not what Slack is expecting.
Ok, after talking with Slack support, it appears (at least) the WebAPIs I am calling don't yet support application/json. These do work with x-www-form-urlencoded.
Looking at this post
I was able to cobble together the following which auth'd successfully:
//up top
var request = require("request");
var querystring = require("querystring");
//...
app.get("/testAuth/test", function(req,res){
console.log("in testAuth/test...sending test message to Slack");
var bToken = process.env.TESTBOT_ACCESS_TOKEN;
var message = {
token: bToken
};
var messageString = querystring.stringify(message);
var messageLength = messageString.length;
var slackMessageURL = "https://slack.com/api/auth.test";
var postOptions = {
headers: {
"Content-length": messageLength,
"Content-type": "application/x-www-form-urlencoded"
},
uri: slackMessageURL,
body: messageString,
method: "POST"
};
request(postOptions, (error, response, body) => {
if(error){
console.log("OOPPPPS....we hit an error in auth.test: " + error);
} else {
console.log("auth.test response: " + JSON.stringify(response));
}
});
res.send("Sent Test...check logs");
});

How to deal AJAX or XRH post request in ExpressJs, where the request use JSON from front-end to back-end?

environment:
-> Front-end: jquery that randle ajax request
-> Back-end: nodejs, expressjs (v.3.4.8).
I trying to create a simple contact form.
my front-end code:
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: { info: JSON.stringify(info) }
}).done(function(retorno){
//do something important
});
this work fine, i tested and on firebug everything from front-end is ok.
but i dont know how to deal with express that need read json from post request.
I just have it:
app.post('/contact', function(req, res){
});
The problem is in:
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
Just change the JSON ' ' to " " and works fine. I came from php and php recognize both ' ' and " " on a JSON, but nodejs just recognize strictly " ".
After some coding the result for a simple example of contact form is:
In a file common.js (front-end):
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {"nome":nome, "email":email, "assunto":assunto, "mensagem":mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: JSON.stringify(info),
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(retorno){
//do something at the end
}
In a file app.js or server.js or anything else (back-end):
var http = require("http")
, express = require('express')
, nodemailer = require('nodemailer')
, app = express();
app.use(express.json());
app.use(express.static(__dirname+'/public'));
app.post('/contact', function(req, res){
var name = req.body.nome;
var email = req.body.email;
var subject = req.body.assunto;
var message = req.body.mensagem;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "your.user#gmail.com",
pass: "your.password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'recipe.email#gmail.com',
subject: subject,
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(80, '127.0.0.2');
From this example: http://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer

Resources