How to extract complete URL without HTTP in Node.js? - node.js

I want to extract the complete URL except HTTP. I have used Domain and url.
Here is my code
var url = require('url');
var domain=require('domain.js');
var url_parts = 'http://static01.nyt.com/images/2014/11/17/business/billboardjump/billboardjump-master675.jpg';
var website=domain(url.parse(url_parts));
var querystring = (url.parse(url_parts, true)).path;
console.log(website+querystring);
But only I am getting
'nyt.com/images/2014/11/17/business/billboardjump/billboardjump-master675.jpg'
instead of
'static01.nyt.com/images/2014/11/17/business/billboardjump/billboardjump-master675.jpg'
Thanks in advance.

just calculate protocol length and drop it:
var u = 'http://static01.nyt.com/images/2014/11/17/business/billboardjump/billboardjump-master675.jpg';
var protocol = url.parse(u).protocol;
console.log(u.slice((protocol + '//').length));

const urlString = "https://stackoverflow.com/questions/26987567/how-to-extract-complete-url-without-http-in-node-js"
const [protocol, urlWithoutProtocol] = urlString.split('://');
console.log(protocol, urlWithoutProtocol)

if (!Str.match(/^(http|https)/i))
Str = "https://" + str;
if the Str doesn't have a ^ at beginning, add it.

Related

How to use 'script' in nodejs

I have this kind of api example and I want to use this in nodejs.
/*
https://code.google.com/archive/p/crypto-js/
https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/crypto-js/CryptoJS%20v3.1.2.zip
*/
<script type="text/javascript" src="./CryptoJS/rollups/hmac-sha256.js"></script>
<script type="text/javascript" src="./CryptoJS/components/enc-base64.js"></script>
function makeSignature() {
var space = " "; // one space
var newLine = "\n"; // new line
var method = "GET"; // method
var url = "/photos/puppy.jpg?query1=&query2"; // url (include query string)
var timestamp = "{timestamp}"; // current timestamp (epoch)
var accessKey = "{accessKey}"; // access key id (from portal or Sub Account)
var secretKey = "{secretKey}"; // secret key (from portal or Sub Account)
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);
hmac.update(method);
hmac.update(space);
hmac.update(url);
hmac.update(newLine);
hmac.update(timestamp);
hmac.update(newLine);
hmac.update(accessKey);
var hash = hmac.finalize();
return hash.toString(CryptoJS.enc.Base64);
}
But the problem is when I use this in Nodejs, I don't know how to require those CryptoJS.
For example, I downloaded CryptoJS file by google. and it is reading by require.
Even though it is read, I don't know which should I read correctly.
Could you help how to solve this problem?
const CryptoJS = require('./CryptoJS v3.1.2/components/enc-base64');
In NodeJS (latest version), you don't even need to download an external library or install from NPM.
Nodejs has crypto built-in library.
const crypto = require('crypto');
var space = " ";
var newLine = "\n";
var method = "GET";
var url = "/photos/puppy.jpg?query1=&query2";
var timestamp = "{timestamp}";
var accessKey = "{accessKey}";
var secretKey = "{secretKey}";
const hash = crypto.createHmac('sha256', secretKey)
.update(method)
.update(space)
.update(url)
.update(newLine)
.update(timestamp)
.update(newLine)
.update(accessKey)
.digest('hex');
console.log(hash);
First of all I dont know why you download file from google? There is very useful npm library. find it here and use it. https://www.npmjs.com/package/crypto-js

ASP.NET Core 2 Url Rewriting middleware to redirect from .xxx to .yyy extension

I want to redirect all request from .com to .net with the same path and route in dot net core.
Same as below code for removing www from start URL:
app.UseRewriter(new RewriteOptions().Add(ctx =>
{
// checking if the hostName has www. at the beginning
var req = ctx.HttpContext.Request;
var hostName = req.Host;
if (hostName.ToString().StartsWith("www."))
{
// Strip off www.
var newHostName = hostName.ToString().Substring(4);
// Creating new url
var newUrl = new StringBuilder()
.Append(req.Scheme)
.Append(newHostName)
.Append(req.PathBase)
.Append(req.Path)
.Append(req.QueryString)
.ToString();
// Modify Http Response
var response = ctx.HttpContext.Response;
response.Headers[HeaderNames.Location] = newUrl;
response.StatusCode = 301;
ctx.Result = RuleResult.EndResponse;
}
}));
You can change your existing code to change the com to net.
if (hostName.ToString().EndsWith(".com"))
{
// change the com to net
var newHostName = hostName.ToString().Substring(0, hostName.ToString().Length - 4) + ".net";
// Creating new url
:
:
}
I have not tested it but it should work.

NetSuite RestLet call from SuiteLet Client

I am trying to call a RestLet webservice/URL from another SuiteScript. As i understand I need to use the http/https module to do so. But I am not able to find some example or steps to do so.
Planning to use this code in SS2.0-
var response = http.post({
url: 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1',
body: myDataObj, // json object
headers: headerObj // json obj
});
The below code works for me.
var nameValue = "arin";
var myDataObj = {
"name" : nameValue
};
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRV158xxxx,nlauth_email=XXXX,nlauth_signature=XXXX,nlauth_role=3';
myRequest.headers["Content-Type"] = 'application/json';
myRequest.headers["Accept"] = '*/*';
myRequest.url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1'; // RESTlet
// URL
myRequest.method = "POST";
myRequest.body = JSON.stringify(myDataObj);
// myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
And reading the response data for JSON return ...
log.debug("Resonse", myResponse.body);
log.debug("Resonse", myResponse.code);
var data = myResponse.body;
var retObj = JSON.parse(data);
log.debug("Resonse Ret city - ", retObj.city);
Here's a basic example of how to do it:
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx#xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3';
myRequest.headers["contentType"] = 'application/json';
myRequest.url = 'https://XXXXXXXXX'; //RESTlet URL
myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
Be careful exposing this on clientside scripts. You don't want to expose your credentials.

Combine two urls into one in node.js

I am trying to combine two urls into a single url.
var access_token = 138def4a4e;
var url = "https://graph.facebook.com/app/?access_token=";
I want the final url to be:
url = "https://graph.facebook.com/app/?access_token=[access_token]";
How to do that in node.js? I tried using url. Resolve but it was of no use.
pls help
TIA
As noted above the selected solution is unsafe.
The following snippet should be preferred:
const accessToken = '138def4a4e';
const someValidUrl = 'https://graph.facebook.com/app/?foo=bar'; // note the querystring param
const url = new URL(someValidUrl);
url.searchParams.append('access_token', accessToken);
console.log(url.href);
As you can notice it's able to manage an Url that contains query parameters and the URLencoding of the querystring params.
I am assuming your code looks like this:
var access_token = '138def4a4e'
var url = 'https://graph.facebook.com/app/?access_token='
If so, the answer is:
var combined = url + access_token
For a final answer of:
var access_token = '138def4a4e'
var url = 'https://graph.facebook.com/app/?access_token='
url += access_token
console.log(url)

How to redirect URL while maintaining all GET parameters using express / Node.js

Using Express/Node.js I receive GET requests with an unknown number of parameters. The names of parameters are not always known in advance. I need to redirect these requests to a new URL while maintaining all existing GET parameters.
ie. I might get any of these
http://example.com/example
http://example.com/example?id=xxx
http://example.com/example?a=xxx&_b=xxx...
etc
which in turn need to be redirected to:
http://newexample.com/example
http://otherdomain.org/sample?type=new&id=xxx
http://newexample.com/sample?a=xxx&_b=xxx...
etc
I've written this code to achieve this, but it feels like this would be common functionality that would already exist in the framework. Is there a better way?
app.get('/example', function(req, res){
var oldParams = ""
var redirectUrl = config.exampleUrlNew;
if (req.originalUrl != null && req.originalUrl.indexOf('?') > 0) {
oldParams = req.originalUrl.split("?")[1];
}
if (oldParams != "" && redirectUrl.indexOf('?') > 0) {
oldParams = "&" + oldParams;
} else {
oldParams = "?" + oldParams;
}
res.redirect(redirectUrl + oldParams)
});
Using the url module
var URL = require('url');
var newUrl = URL.parse(oldUrl, true); // true to parse the queryString as well
newUrl.host = null; // because
newUrl.hostname = 'newexample.com';
newUrl.search = null; // because
newUrl.query.newParam = 'value';
newUrl = URL.format(newUrl);
There's a quirk that you have to set .host property to null for .hostname property to take precedence, because acc to the docs setting the hostname only works if the host isn't present, which it is since it's parsed from oldUrl. Ditto for .search and .query

Resources