I'm making the front end of a webpage where some json is needed for now I'm not doing the back so I made a file called it map.json and placed it on my server.
I'm working with node.js as a server so in the public folder I created a new folder named it jason and saved the file there.
Now I'm making an ajax call to this file, but the program isn't finding it, and when I go to public from the google chrome I don't see the json folder.
What do I have to do to be able to see this file and upload it as it was an ajax call to the server?
here is my jquery code, its in a file in public/javascript:
$.ajax('/../json/map.json', {
cache: false,
dataType: "json",
success: function(json) { ... code ... }
});
I really don't know how or what file should I modify in noje.js
Thanks!
The URL path used is technically invalid. Following a leading / with .. attempts to reach the parent directory of the domain's root path, which doesn't exist.
Though the browser may simply ignore the .., you should still choose one or the other -- either specify the path from root:
$.ajax('/json/map.json', {
// etc.
});
Or relative to the URL path of the current page (e.g., /some/page):
$.ajax('../json/map.json', {
// etc.
});
You've also stated that that the folder is named "jason" while the request includes /json/.... One may simply be a typo, but make sure they match.
And, assuming you're using the static() middleware, the URL will need to match the prefix specified (or lack of one):
app.use(express.static(__dirname + '/public'));
// $.ajax('/json/map.json', ...);
app.use('/public', express.static(__dirname + '/public'));
// $.ajax('/public/json/map.json', ...);
Related
We are using Firebase Google Cloud Storage Bucket to store our files.
When the logged in user wants the download the file kept inside certain folder
Eg: 123/admin/1469611803143/123.xlsx
The url generated will be
https://firebasestorage.googleapis.com/v0/b/MYWEBSITE.appspot.com/o/123%2Fadmin%2F1469611803143%2F123.xlsx?alt=media&token=whatever_alpa_numeric_token
As I download this file the file name will be 123%2Fadmin%2F1469611803143%2F123.xlsx
and not 123.xlsx
We have tried using download attribute to change the file name
but this did not change the file name to 123.xlsx
Please HELP
I'm pretty new with firebase but I achieved this with the following code :
var storageRef = firebase.storage().ref();
var child = storageRef.child("your path");
var uploadTask = child.put(<file>);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
function(snapshot){
// HANDLE TASK PROGRESS
},
function(error){
// HANDLE ERROR
},
function(){
// UPLOAD SUCCESSFULL
var newMetadata = {
contentDisposition : "attachment; filename=" + fileName
}
child.updateMetadata(newMetadata)
})
This is (fortunately or unfortunately) intended behavior. Technically, files in Firebase Storage are stored with the full path (so 123%2Fadmin%2F1469611803143%2F123.xlsx is actually the file name--the slashes and percent escaping are part of the name, and are only represented as path separators in the UI), which is how we get this behavior.
We're likely to modify how downloads work in the future (in that we'll truncate the name), but we've been busy fixing other bugs and polishing higher priority pieces.
See, I was training with Node (and TS btw), and tried to do a trivial server with multiple request/response options. But I have a problem I don't know how to solve without using Express (at least for now I don't want to use it).
I have a HTML file which requests an image file. While in the IDE, everything looks like it's going to work, but when the server is running, the image cannot be found. It's kind of obvious why: The HTML makes a request the server doesn't know how to handle. Thing is, I thought the document could refer to other files without the need of talking to the server.
What is an elegant and working solution for my problem?
Thanks in advance.
import * as http from 'http'
import * as fs from 'fs'
fs.readFile('doc/kmCNHkq.jpg', function (err, data) {
let binaryimg = new Buffer(data).toString('base64');
if (err) throw err;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.end(data);
console.log("Delivered the jpeg");
}).listen(8000);
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(binaryimg);
console.log("Delivered base64 string");
}).listen(8124);
console.log("Unless bug, both servers are listening");
});
fs.readFile('doc/index.html', function(err, data) {
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data)
}).listen(80);
console.log("HTML server is running")
})
(main.ts; Targets ES6)
<html>
<head>
</head>
<body>
<img src="doc/kmCNHkq.jpg"/>
</body>
</html>
(index.html)
Observation: I used to leave the HTML file in '../doc/' and resources on '../img/' however it seems that the HTML uses relative paths, so I copied the image into HTML's folder. If the solution also made it so I could leave the resources on their's respective folders it would be much appreciated.
#Edit:
Now I'm using this switch/case request handler. Working as expected, the HTML's request for the image is interpreted as a normal request (which may not end up scaling well, idk, but screw it). Thanks a lot!
import * as http from 'http'
import * as fs from 'fs'
var stream: fs.ReadStream,
folder = __dirname.substr(0, __dirname.length - 3);
http.createServer(function(req,res) {
switch (req.url){
case('/jpeg'):
stream = fs.createReadStream(folder + 'img/kmCNHkq.jpg');
stream.pipe(res);
console.log("Delivering the jpeg");
break;
case('/base64'):
fs.readFile('img/kmCNHkq.jpg', function (err, data) {
let img64 = new Buffer(data).toString('base64');
if (err) throw err;
res.end(img64);
console.log("Delivered base64 string");
})
break;
case('/html'):
stream = fs.createReadStream(folder + 'doc/index.html');
stream.pipe(res);
console.log("Sending the docs");
break;
default:
console.log("Shit happens");
}
}).listen(80)
(main.ts)
<html>
<body>
<img src="jpeg"/>
</body>
</html>
(index.html)
Short answer:
You won't be able to refer to specific resources on the server (such as your image) unless your server knows how to respond to those requests for that content. It looks like you can probably make your example work easily immediately though by changing the image src to just http://localhost:8000 though.
Longer answer:
Using 'doc/kmCNHkq.jpg' as the src for your image tells your browser that when it loads the page, it should go to the server it got the page from, and ask it for the 'doc/kmCNHkq.jpg' resource. If you specify a full URL including the protocol (the http://) then it will be absolute, instead of relative, so you can request from a different server than the one that served the page.
The servers that you've written don't actually look at the path of the file that's requested though (req.url), and actually they just always return the same content. If you connect to http://localhost:80 (the third server you've created above), and do request that jpg you'll still just get given the same HTML data of the page, because it just runs the two lines in your createServer call at the end of your example. You have written a server that always returns the image however above (the first server), just running on a different port, which is why the above solution works.
Just using that existing server is the simplest solution. The far more conventional approach though is to have just a single HTTP server running on a single port (instead of the 3 you have) and to use req.url to decide what data to return.
Traditionally for static content that means mapping a requested path directly onto the layout of the files on disk, so that requesting doc/abc.jpg looks for a doc folder in the server's directory, and returns the data from abc.jpg therein. That's not required necessarily at all though, and your server can interpret those paths however you like, to return content from anywhere.
(Note than none of this is really anything to do with TypeScript, or even much to do with Node.js. This is really just the essentials of how HTTP servers and browsers interact, and it would be almost identical with any other backing technology. I'd take a look more into the general HTTP and browser details if you're looking to get more background on this.)
I'm developing an extension to the Chrome and I'd like to filter WebNavigation.OnCompleted event so that it's only fired on certain domains.
I'm using it like this:
chrome.webNavigation.onCompleted.addListener(function(details) {
// some code here...
}, {
url : {hostEquals : 'www.foo.bar'}
});
That works. Then I started testing this on a test page, which is located on my local computer. That's when I ran into the problem: what's the value of the filter when URL points to a file located on the local computer (i.e. what's the hostname of a local file from Chrome event filter perspective):
file:///home/usr/testfile.html
I know, the URL doesn't really contain a hostname, but I think it should be possible to filter these kind's of addresses too. I've tested different variations, like 'file:///', 'localhost' and '/' but none of them seem to get the job done. Leaving the filter empty equals no filtering at all.
The extension works fine without the filter, but I need to get this system to work with it.
To match a file URL that starts with "/home/user/", just use urlPrefix, e.g. as follows:
chrome.webNavigation.onCompleted.addListener(function(details) {
// Some code here...
}, {
url: [{
hostEquals: 'example.com',
}, {
// Note: This filter will only match if
// 1) You've declared the "file://*" or "<all_urls>" permission
// in manifest.json, and
// 2) You've visited chrome://extensions and ticked the checkbox
// "Allow access to file URLs" at your extension.
urlPrefix: 'file:///home/user/'
}],
});
For other filters, see the documentation at chrome.webNavigation.onCompleted.
PS. The host name of a file:-URL is whatever that comes between the file:// and the path. In case of file:///, it's an empty string.
I have a local json file in my client folder that contains information for <option>s in a <select> tag.
I tried using ajax to fill up <option>s but my app keeps crashing.
What is the proper way to get information out of a local json file in meteor?
To get information from the server you need to use a Meteor method.
To read local file you need to use assets.
For example, assuming your file is /private/options.json:
server side
Meteor.methods({
getOptions: function() {
return Assets.getText('options.json');
},
});
client side
var loadOptions = function() {
Meteor.call('getOptions', function(error, result){
fillOptions(JSON.parse(result));
});
};
I had the same problem, I needed to load labels for the client.
Instead of calling the server, the client can directly perform a HTTP call and retrieve the file.
Put your file into the public directory
Use the HTTP API to get your file
HTTP.get('/yourFile.json', {}, function(error, result) {
var parsedFile = JSON.parse(result.content);
});
If you are using Iron router be sure to wait for the result before displaying your page with a waitOn.
As the call is asynchronous, it might take some time to get your result.
Let's say I have a JSON file stored within my extension called settings.json. I can get the URL of the file using:
chrome.extension.getURL("settings.json");
But now that I have the URL, how do I actually load the contents of that file so I can JSON.parse it and use it? The reason I'm doing this is that there is a server component, and I want to make deployment and testing on multiple servers easier (dev, staging, production, etc.) Alternatively if there's a way to add custom attributes to the manifest.json and access them, that would also work.
If you make your setting.js look like:
var settings = {"param":value,...};
Then you can just include it on a background page and use settings variable:
<script src="settings.js"></script>
If you want to have pure json in your file without assigning it to any variables then you can load it using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange; // Implemented elsewhere.
xhr.open("GET", chrome.extension.getURL('/config_resources/config.json'), true);
xhr.send();
or if you included jquery into your project:
$.getJSON(chrome.extension.getURL('/config_resources/config.json'), function(settings) {
//..
});
(btw using chrome.extension.getURL is required only if you are accessing a file from a content script, otherwise you can just use relative path /config_resources/config.json)
I can verify that requesting the resource from an XHR in the background page works as previously described. Just be sure to add 'self' to the connect-src portion of your content_security_policy.