What is the hapi equivalent of res.writehead and res.write? - javascript

I am using ccavenue npm module to integrate payment gateway in my website.
The problem with that modules is that it uses res.write and res.writehead while the res variable passed to the module is generated by hapi and thus generating a error. So, what is the hapi equivalent of res.writehead and res.write.
Here is my hapi code:
var ccavenue = require('ccavenue');
ccavenue.setMerchant("******");
ccavenue.setWorkingKey("*******************");
ccavenue.setRedirectUrl("/redirect-url");
module.exports = function(plugin, options, next) {
plugin.route({
method: 'GET',
path: '/checkout',
handler: function(request, reply) {
var param = {
billing_cust_address: 'Bangalore',
billing_cust_name: 'Nitish Kumar'
};
ccavenue.setOrderId("8981455644");
ccavenue.setOrderAmount("1000");
ccavenue.setOtherParams(param);
ccavenue.makePayment(reply);
}
});
}
This is the module function:
function makePayment(res) {
var errors = helper.checkRequiredField(config);
if(errors.length > 0) {
throw new Error(errors);
}
var Checksum = helper.getCheckSum(config.merchantId, config.orderAmount, config.orderId, config.redirectUrl, config.workingKey); //This function is to verify
var body = "<form method='post' name='checkout' id='checkout' action='https://www.ccavenue.com/shopzone/cc_details.jsp'>" +
"<input type=hidden name='Merchant_Id' value='" + config.merchantId + "'>" +
"<input type=hidden name='Amount' value='" + config.orderAmount + "'>" +
"<input type=hidden name='Order_Id' value='" + config.orderId + "'>" +
"<input type=hidden name='Redirect_Url' value='" + config.redirectUrl +"'>" +
"<input type=hidden name='Checksum' value='" + Checksum + "'>" +
"<input type=hidden name='TxnType' value='A'>" +
"<input type=hidden name='ActionID' value='TXN'>";
for(var key in otherParams) {
body += "<input type=hidden name='"+ key +"' value='" + otherParams[key] + "'>";
}
body += "</form><script type='text/javascript'>" +
"document.getElementById('checkout').submit();" +
"</script>";
res.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/html'
});
res.write(body);
res.end();
}
This is the error:
Debug: internal, implementation, error
TypeError: Uncaught error: res.writeHead is not a function
at Object.makePayment (/home/satnam-sandhu/Workstation/cuboid.io/servers/web/node_modules/ccavenue/index.js:59:8)
at Object.plugin.route.handler (/home/satnam-sandhu/Workstation/cuboid.io/servers/web/ccavenue/index.js:21:15)
at Object.exports.execute.internals.prerequisites.internals.handler.finalize [as handler] (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/handler.js:101:51)
at /home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/handler.js:32:23
at internals.Protect.run.finish [as run] (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/protect.js:60:12)
at exports.execute.finalize (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/handler.js:26:22)
at each (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/request.js:401:16)
at iterate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:36:13)
at done (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:28:25)
at internals.Auth.test.internals.Auth._authenticate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/auth.js:222:16)
at internals.Auth.test.internals.Auth.authenticate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/auth.js:197:17)
at each (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/request.js:401:16)
at iterate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:36:13)
at done (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:28:25)
at /home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/protect.js:50:16
at wrapped (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/hoek/lib/index.js:875:20)

I assume you are using an older version of hapi 17.0.0, in order to to reply with html use https://github.com/hapijs/vision. Also this example tutorial should help
https://futurestud.io/tutorials/hapi-how-to-render-views. Hapi will do most of the work for you. If you want to use node's res and req http server objects you need to expose the raw request and response objects from hapi's internals as documented here https://hapijs.com/api/16.5.2#request-properties under raw property.

Related

visual studio with javascript debugging showing different behaviour while running directly and by running in debug mode

in javascript visual studio database programming, i am fashing very unusual behaviour of program execution.
i have javascript code like this:
<script type="text/javascript">
function GetValue6(id1, id2, id3) {
var user = {};
user.Username = $("[id*='" + id1 + "']").val();
user.Password = $("[id*='" + id2 + "']").val();
alert(user.Username);
$.ajax({
type: "POST",
url: '<%= ResolveUrl("Default.aspx/SaveUser") %>',
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
},
error: function () { alert("There was an error."); }
});
return false;
}
</script>
and code behind file like this:
child.Text = "<input type='text' id='" + TextGUID1 + "' value='" + rows[i]
["Area"].ToString() + "'/>
<input type='text' id='" + TextGUID2 + "' value='" + rows[i]
["Area"].ToString() + "'/>
<input type = 'button' id='" + ButtonGUID3 + "' onclick=\"GetValue6('" +
TextGUID1 + "','" + TextGUID2 + "','" + ButtonGUID3 + "')\" value='Save'
/>
public static void SaveUser(User user)
{
string constr =
ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users2
VALUES(#Username, #Password)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Username", user.Username);
cmd.Parameters.AddWithValue("#Password", user.Password);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a very strange behaviour that i am facing, when i run above code by clicking "Save" button then i face error alert message "There was an error.". But when i run the program in debugging mode and press F10(Step over new function call) then i get the alert message "User has been added successfully." and user gets insert in the corresponding table. moreover one strange thing is that when e get the error message "There was an error.", even then the corresponding user get inserted into the table successfully.
please guide me where i am wrong and how can i get the username gets inserted with the proper successful message.
When you run the script onclick, also you make and a post back - here, try to return false to avoid the post back - write this
onclick=\"GetValue6(....); return false;\"
or this
onclick=\"return GetValue6(....);\"
because inside the GetValue6 you return false.
And when you make debug, the program waits/hold the post back because of the debug step by step - that's why its success.

django csrf token with js

i'm trying to add to the html page a form with js (like the html token {% csrf_token %} when loading the page does):
table += "<td><form action='' method='post'>";
table += "<input type='submit' value='Delete?' />";
table += "</form></td>;
$("#tbody").append(table);
my problem is that i get a csrf validation error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
i tried to add a custom csrf token:
var buf = new Uint8Array(1);
window.crypto.getRandomValues(buf);
table += "<input type='hidden' name='csrfmiddlewaretoken' value='" + buf[0] + "'>";
but i still get an error.
i also have in my js file the following code (which i got from the django website - and i don't know how it actually works..):
//enable csrf post ajax
//This function gets cookie with a given name
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
/*
The functions below will create a header with csrftoken
*/
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain &&
(!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url)))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
is there a way to add a csrf token with js the way i tried or it can not be?
The Javascript code provided by django for csrftoken extraction assigns csrftoken value to a variable named csrftoken
You can access it anywhere by its variable name, like this:
table += "<input type='hidden' name='csrfmiddlewaretoken' value='" + csrftoken + "'>";
Make sure you've included the js provided by django in your page before accessing csrftoken
Also, as #Sander pointed out, if you're using inline JS you can directly use csrf_token template tag instead.
table += "{% csrf_token %}";
Is the js added as inline js to your django template?
In that case you can do:
table += "<td><form action='' method='post'>";
table += "{% csrf_token %}";
table += "<input type='submit' value='Delete?' />";
table += "</form></td>;
$("#tbody").append(table);

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

Trying to pull location info on first connection in linkedin with javascript api

I have working code for pulling my connections info from Linkedin.
However, whenever I try to pull location I get strange results.
This code works but you will see 'object OBJECT' where location is supposed to be.
<html lang="en">
<head>
<title>LinkedIn Industries</title>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: xxxxxxx
onLoad: onLinkedInLoad
scope: r_network,r_emailaddress,r_fullprofile,r_basicprofile,r_contactinfo
</script>
</head>
<body>
<p>This example demonstrates how to retrieve a user's connections. It also uses the LinkedIn auth events (load, login, logout) to control behavior.</p>
<!-- NOTE: be sure to set onLoad: onLinkedInLoad -->
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", function() {onLinkedInLogin();});
IN.Event.on(IN, "logout", function() {onLinkedInLogout();});
}
function onLinkedInLogout() {
setConnections({}, {total:0});
}
function onLinkedInLogin() {
// here, we pass the fields as individual string parameters
IN.API.Connections("me")
.fields("id", "firstName", "lastName", "pictureUrl", "publicProfileUrl","location:(name)")
.result(function(result, metadata) {
setConnections(result.values, metadata);
});
}
function setConnections(connections) {
var connHTML = "<ul>";
for (id in connections) {
connHTML = connHTML + "<li><a href=\"" + connections[id].publicProfileURL + "\">";
/* picture url not always there, must be defensive */
if (connections[id].hasOwnProperty('pictureUrl')) {
connHTML = connHTML + "<img align=\"baseline\" src=\"" + connections[id].pictureUrl + "\"></a>";
} else {
connHTML = connHTML + "<img align=\"baseline\" src=\"http://static02.linkedin.com/scds/common/u/img/icon/icon_no_photo_80x80.png\"></a>";
}
connHTML = connHTML + " <a href=\"" + connections[id].publicProfileUrl + "\">";
connHTML = connHTML + connections[id].firstName + " " + connections[id].lastName + "</a>";
connHTML = connHTML + " (Location: " + connections[id].location + ")</li>";
}
connHTML = connHTML + "</ul>";
document.getElementById("connectionsdata").innerHTML = connHTML;
}
</script>
<script type="IN/Login">
<div id="connectionstest">
<p>Current User's Connections:</p>
<div id="connectionsdata"></div>
</div>
</script>
</body>
</html>
The main issue really exists in location, in the documentaion this should be replaced with location.name, however, whenever I do this I get nothing back, although I can see that there is a XHR response with a json, which has:
location:{"name":"Dublin etc"}
Please help solve the mystery of the hidden location
EDIT: 5/23/2013-
In Chrome's Developer tools I can see a message saying (Uncaught TypeError: Cannot read propertry 'name' of undefined - hopes this help someone help me
When I look in the console of the chrome developer, there is more detail on the above uncaught type error: Uncaught TypeError: Cannot read property 'name' of undefined linkedconnect.html:55
setConnections linkedconnect.html:55
(anonymous function) linkedconnect.html:36
Sslac.Class.Constructor.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.b framework:3242
(anonymous function) framework:173
Sslac.Class.Constructor.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.Method.storedFailureResults
framework:3247
(anonymous function) framework:173
g framework:3135
pub.incoming framework:801
_window_onMessage framework:566
Maybe you can temporary replace the code setting html with a log of what the connections array really contains:
//connHTML = connHTML + " <a href=\"" + connections[id].publicProfileUrl + "\">";
//connHTML = connHTML + connections[id].firstName + " " + connections[id].lastName + "</a>";
//connHTML = connHTML + " (Location: " + connections[id].location + ")</li>";
console.log(connections[id]);
When you log an object you can click on it to inspect it's properties, maybe some of the items simply do not contain a location. In that case you can try:
function setConnections(connections) {
var connHTML = "<ul>",
tmpLocation;
.....
tmpLocation= (connections[id].location && connections[id].location.name)
?connections[id].location.name:"Unknown";
connHTML = connHTML + " (Location: " + tmpLocation + ")</li>";
As the error message is suggesting you are displaying an object when you are actually trying to display a string. Therefore you need to to pick the correct property of that object:
connHTML = connHTML + " (Location: " + connections[id].location.name + ")</li>";

web service not working on safari

I have created a web service and call it from my javascript using ajax. It works on internet explorer to some extent but fails when i call try to run it on safari or firefox. Does anyone know why?
Here is my js code:
function GetTopApps() {
var serviceUrl = "http://localhost:2975/GetData.asmx?wsdl";
var soapMessage ='<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><HomeScreenApps xmlns="http://tempuri.org/" /></soap:Body></soap:Envelope>'
$.ajax({
url: serviceUrl,
type: "post",
datatype: "xml",
data: soapMessage,
complete: GenerateList,
contentType: "text/xml; charset=\"utf-8\""
});
return false;
}
function GenerateList(xmlHttpRequest, status) {
$(xmlHttpRequest.responseXML)
.find('HomeScreenAppsResult')
.each(function () {
parseXML(xmlHttpRequest);
});
}
function parseXML(xmlHttpRequest) {
var xmlDoc = xmlHttpRequest.responseXML;
var appIdArray = xmlDoc.getElementsByTagName('application_id');
var appNameArray = xmlDoc.getElementsByTagName('application_name');
var appRatingArray = xmlDoc.getElementsByTagName('average_rating');
var appCount = appIdArray.length;
var appList = document.getElementById('TopApps');
var htmlString = "<small><small><small><small><small><small><small><ul data-role='listview' data-filter='false' id='list'>";
for (i = 0; i < 5; i++) {
htmlString = htmlString + "<li><a id='" + appIdArray[i].xml + "' onclick='AppSelected(id);'>";
htmlString = htmlString + "<img src='' alt='Logo' class='ListAppLogo'>";
htmlString = htmlString + "<h3>" + appNameArray[i].xml + "</h3>";
htmlString = htmlString + "<p>" + appRatingArray[i].xml + ".0/5.0</p>";
htmlString = htmlString + "<input type='hidden' value='" + appIdArray[i].xml + "'></a></li>";
}
htmlString = htmlString + "</ul></small></small></small></small></small></small></small>";
appList.innerHTML = htmlString;
$('#list').listview();
}
You can find out yourself by using a Javascript debugger such as Firebug for Firefox, or the built-in web inspector for Safari.
First check your javascript error log and console for any parsing errors, if there are none use breakpoints to step through your code to see how it executes. If you find anything specific which you dont understand feel free to ask about that.
Also consider the error might be in your webservice, not where you call it.
Safari is more secure than IE or Chrome.
You would easily be able to run on chrome or IE because safari needs certificate of that server whose service you are calling.
ensure that you create certificate for that server if you wanted to run that on mac or Iphone

Categories