I am making an ajax call:
var hostUrl = location.hostname;
$.getJSON(hostUrl + "/DataMatrix/ItemTypeList/" + $("#filter > option:selected").attr("value"),
function (dataValue) {
This is what I get in my network tab:
http://localhost:50020/localhost/DataMatrix/ItemTypeList/5001
Localhost gets appended on top of local host, however in production it works fine as url formed is (xyz: host placeholder).
xyz/DataMatrix/ItemTypeList/5001
Once I remove host url then it works great in local too, but fail in production:
$.getJSON("/DataMatrix/ItemTypeList/" + $("#filter > option:selected").attr("value"),
function (dataValue) {
How to handle such scenario during development so that I don't have to change the string when I am handing over the files to deployment team.
just remove the leading "/" ie:
$.getJSON("DataMatrix/ItemTypeList/" ...
This is because the the browser will automatically interpret the URL as being relative to the current host (e.g. "http://localhost:50020/" or "https://myhost.com/") and prepend that to your stated URL.
So if you put "DataMatrix/ItemTypeList" in your URL when deployed on "https://myhost.com", the ajax call will automatically make the call to "https://myhost.com/DataMatrix/ItemTypeList".
Related
I'm writing a node.js application with client-side javascript that uses fetch to get data from the node API that I wrote. I want to be able to put that application on any site (URL) without changing anything in the javascript. My current code goes something like fetch("http://localhost:8080/data.json"). If I wanted to deploy onto Heroku, for example, I would have to change that. Is there a way to overcome this fact?
Window location might do the trick, if I am understanding correctly. Set it into a variable like this:
For browser:
If the hostname is http://localhost:8000, using this:
// http://localhost:8000/data.json
var url = window.location.hostname + "/data.json";
fetch(url)
Heres another example.
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Result is
Page location is https://www.w3schools.com/js/js_window_location.asp
More info:
https://www.w3schools.com/js/js_window_location.asp
I see you wanted NodeJS, for server
var os = require("os");
var port = process.env.PORT || 8000
var url = os.hostname;
var final = url + ":" + port
// localhost:port
var hostname = os.hostname();
I am working on a project which I share with someonelse.
I have my host set up as http://dev.foobar which maps to a folder called foobar.com and I have no issues with my code, it all works as intended. However the other person has the same named folder foobar.com, but hasn't set up virtualhost, so he is using http://localhost/foobar.com
So, inside the code I have to send an ajax request to a URL http://dev.foobar/wp-admin/admin-ajax.php" however this won't work for the other guy, since his would be http://localhost/foobar.com/wp-admin/admin-ajax.phpso right now I am using this code to get the host and append the url wp-admin/admin-ajax.php
function get_host() {
if (window.location.hostname == "localhost") {
var host = "https://localhost/foobar.com/";
} else {
var host = "https://" + window.location.hostname
}
return host
}
And I am send request to ajax like this
var ajaxURL = get_host() + "/wp-admin/admin-ajax.php";
The problem with the function is that I am hard-coding foobar.com and I am not sure if there is another way to do this
I am trying use only Node (no additional npms or express). Here is my current route handler:
function requestHandler(req, res) {
var localFolder = __dirname + '/views/',
page404 = localFolder + '404.html',
fileToServe = "";
if(/\/posts\/\d+/.test(req.url)){
fileToServe = __dirname + req.url.match(/\/posts\/\d+/) +'.json';
fs.stat(fileToServe, function(err, contents){
if(!err && contents){
res.end(templateEngine('post',fileToServe));
} else {
res.end(templateEngine('error', err))
}
});
} else if (/\/posts\//.test(req.url)){
} else if (/.+[^\W]$/.test(req.url)){
fileToServe = __dirname + '/views' + req.url.match(/\/.+[^\W]$/gi);
fs.stat(fileToServe, function(err, contents){
if(!err && contents){
res.end(fs.readFileSync(fileToServe));
} else {
res.end(templateEngine('error', err))
}
});
}
}
I have two questions:
In one of my views if have a <link> tag with a css file. When I go straight to the path, it is served (this is the regex that catches it: /.+[^\W]$/.test(req.url)). However, as mentioned, one of my views built from the template engine uses the css file.
How does the browser work when it sees the link tag? Does it send a GET request to my local server (node)? If it does, why doesn't my server send a response back? When I go directly to the link, it sends the response perfectly fine.
Furthermore, when I try going to the page that uses the css file in the link tag, it just hangs on an empty page. When I kill the server, it says it never received a response (once again, when I go to the link directly, I get the proper file).
Do I have to re-organize my routes? Serve static files separately?
How does the browser work when it sees the link tag? Does it send a GET request to my local server (node)?
Yes. Browser creates the full URL based on the current URL and makes an HTTP GET request like it does for any other resource.
If it does, why doesn't my server send a response back? When I go directly to the link, it sends the response perfectly fine.
All evidence suggests that your page which links to the css is not being captured in the handler if-blocks. Try putting a couple of console.logs, one right inside the requestHandler and the other inside in the block which is supposed to handle the page request. I think you will only see one log show up in the server console.
I am building an app with Phonegap and jQuerymobile. The app roughly works like this:
1) The app downloads a ZIP file from a public server and then unzips them to a local folder. I got the local folder path from fileSystem.root.toNativeURL() (in OS, it's something like this: file://var/mobile/Container/Data/Application/xxxx/Documents/)
2) App redirects to HTML that was unzipped in local folder (ex: file://var/mobile/Container/Data/Application/xxxx/Documents/index.html)
I am now facing issues b/c inside the index.html file, all the links are absolute path (ex: Link). This breaks all the links since (I assume) they are all now pointing to file://content/index2.html instead of file://var/mobile/Container/Data/Application/xxxx/Documents/content/index2.html.
My question is, how should I handle the links? I am thinking i should just rewrite all the links to force prepend the local folder URL in front of it. Is there a better way?
And if rewriting links is the way to go, how can I do this with jQuerymobile? I did this in jQuery which seems to work http://jsfiddle.net/jg4ouqc5/ but this code doesn't work in my app (jQueryMobile)
When you are loading index.html, you are getting file://some_path/..../index.html as your base URL. Any links which will be encountered now own-wards can be resolved in relation to the base URL.
You would know your scenario better. There could be multiple ways in which this can be fixed.
Have a contract with the CMS/Code generator. Links should always be generated either Relative to the base URL or Absolute. The links you are getting in the page are wrong - Link it ideally should be Link or fully qualified like https://www.google.com.
If you want to change the URL then you can use native code to change it after unzipping the content. It will be really straight forward.
If you want to change the URL in browser then you will have to persist the base url and then take care of couple of things:
a. absolute urls - In your case you can just check the window.location.protocol, if it starts with 'http' and then skip it.
b. sub-directories
Here is a small I have written:
Note: I have not tried this code and you might have to change it according to your need.
$(document).ready(function(){
var base_file_name = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
//In index.html (persist this value in native)
var baseUrl = window.location.href.replace(base_file_name, "");
$("a").each(function () {
this.href = baseUrl + this.pathname;
$(this).click(function (e) {
e.preventDefault();
alert(this.pathname);
window.location.href = this.href;
});
});
});
The example you linked should work, make sure you have the <base> set correctly and that you are using the correct string to replace.
Yeah, your going to have to normalize all URL's when your page loads. I can't test with phonegap right now, but your basePath will need to be one of the following:
The file path as you described in your answer (not likely)
window.location.origin (optionally including window.location.pathname)
CODE:
// mini dom ready - https://github.com/DesignByOnyx/mini-domready
(function(e,t,n){var r="attachEvent",i="addEventListener",s="DOMContentLoaded";if(!t[i])i=t[r]?(s="onreadystatechange")&&r:"";e[n]=function(r){/in/.test(t.readyState)?!i?setTimeout(function(){e[n](r)},9):t[i](s,r,false):r()}})
(window,document,"domReady");
domReady(function () {
var anchors = document.getElementsByTagName['a'],
basePath = /* get your base path here, without a trailing slash */;
Array.prototype.forEach.call(anchors, function( anchor ){
anchor.setAttribute('href', basePath + anchor.getAttribute('href'));
});
});
Remove the forward slash from the beginning of your links.
href="content/index2.html">
I have a web page that needs to check the contents of a file that resides on the same partition as the origin URL.
My origin URL is: file:///C:/work/run/report/index.html
This URL has a frame that shows another URL: file:///C:/work/run/report/dir1/dir2/frame.html
This frame tries to send a get request to file:///C:/work/run/log/log.html (using relative path: "../../../" + log/log.html) using the following excerpt:
$.get("../../../" + log/log.html, function( data ) {
checkIfLogFileContentsIncludeBookmark(data);
},"html");
This fails.
However, when trying to perform the same get to a URL that resides inside the origin URL's directory: file:///C:/work/run/report/log/log.html (using relative path: "../../" + log/log.html), it works fine, using the same code:
$.get("../../" + log/log.html, function( data ) {
checkIfLogFileContentsIncludeBookmark(data);
},"html");
Is there some known limitation of jQuery.get(), JavaScript in general or URLs in general I'm missing?