How to fix 'Unexpected token < in JSON at position 0'? - javascript

I'm trying to share a website I've done using GitHub pages, but I'm having troubles loading the JSON files.
This is for a friends game server website, using HTML 5, JavaScript and JSON, I've tried running it from localhost and it worked perferctly fine.
The issue actually is a SyntaxError : Unexpected token < in JSON at position 0 and when I try to look for the JSON file in chrome debugger I can't see my JSON files to check where the probleme could be coming from.
The JSON file :
{
"header_menu_games": "Games",
"header_menu_home": "Home",
"header_menu_rules": "Rules",
"header_menu_support": "Support",
"header_serverip_text": "Server ip:",
"header_serverip_copy_btn": "Copy"
}
The JavaScript code I use to translate :
if (isLanguageAvailable) {
var myRequest = new Request(`../../src/lang/${userLang}.json`);
console.info(`User language (${userLang}) is available`);
} else {
var myRequest = new Request("../../src/lang/en.json");
console.info(`The user language (${userLang}) is unfortunately not available`);
}
console.log(myRequest);
fetch(myRequest)
.then(resp => {
resp.json()
.then(data => {
document.getElementById("lang-header_serverip_text").innerHTML = data.header_serverip_text;
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
Console error:
JavaSript catch error:
The full code is available on GitHub.

I believe you're receiving a 404 error because you're pointing your link at the repository location instead of the actual content. You were linking to a nonexistent link: https://vianpyro.github.io/src/lang/en.json
You can do this one of two ways:
Link to the raw version of the file from the repository
Point at the correct location from your friend's domain
1. Linking to the Raw Version
In github, click on Raw and it should open a page containing the actual JSON.
You'll see that the actual link to the content is: https://raw.githubusercontent.com/Vianpyro/Aycraft/master/src/lang/en.json
2. Linking to the hosted location
Part of your original problem was that you weren't pointing at the right path. Your friend's site is hosted at https://vianpyro.github.io/Aycraft and not https://vianpyro.github.io/.
This means that the base url of the site is https://vianpyro.github.io/Aycraft and everything in the path has to follow that. You have to include the /Aycraft after the domain name since that is the baseurl of the site.
The correct url would be:
https://vianpyro.github.io/Aycraft/src/lang/en.json

Related

How to open a preview file (pdf, docx, txt, etc.) in another page of the browser using Angular and Java

I am developing a web application using Angular 7 and Java 8. I am uploading a file (pdf, docx, txt etc...), but the problem is that I can't open it in another page of the browser through a RESTful web service. I am getting the error 415 Unsupported Media Type. I have tried with the POST and GET method whitout any success. These are the snippets of the code, front-end and back-end:
Angular component (method called by a button passing the path + filename example : C/doc/foo.pdf)
download(doc) {
this.service.downloadFile(doc.path).subscribe(response => {
if(response) {
let blob = new Blob([response], { type: 'text/json; charset=utf-8' });
const url= window.URL.createObjectURL(blob);
window.open(url);
}
});
}
Angular service
downloadFile(path): Observable<Blob> {
const url = '/download';
return this.http.post<Blob>(url, path, { responseType: 'blob' as 'json' });
}
Java Controller
#PostMapping(value = "download", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
#ResponseBody
public byte[] download(#RequestBody String path) {
try {
return this.provvedimentoService.getDownload(path);
} catch (IOException | EgesException e) {
e.printStackTrace();
return null;
}
}
Java Service
public byte[] getDownload(String pathFile) throws EgesException, IOException {
Path path = Paths.get(pathFile);
if(path.toFile().exists())
return Files.readAllBytes(path);
else
throw new EgesException(EgesExceptionConstants.WARNING_ACT_NOTFOUND_EXCEPTION);
}
You can't. Browsers don't have any built-in way to view Word docs so unless the user has configured their browser to open it with some plugin (which 99% of the world hasn't done), the browser will prompt them to download the file.
No browsers currently have the code necessary to render Word Documents, and as far as I know, there are no client-side libraries that currently exist for rendering them either.
However, if you only need to display the Word Document, but don't need to edit it, you can use Google Documents' Viewer via an <iframe> to display a remotely hosted .pdf/ .doc/.docx /.txt etc
<iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>
Many people used this methods to view their documents file. you can check here:How to display a word document using fancybox
<iframe width="100%" height="300px" src="https://docs.google.com/gview?url=http://index-of.co.uk/Google/googlehacking.pdf&embedded=true"></iframe>
You can add your document file URL like this
https://docs.google.com/viewer?url=<url for your file>&embedded=true
Here will be your file url <url for your file>
You have another way to view the .pdf/ .doc/.docx /.txt etc like google iframe system of Microsoft Document viwer webapp.
You can use it like this.
<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://writing.engr.psu.edu/workbooks/formal_report_template.doc' width='80%' height='800px' frameborder='0'></iframe>
<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://writing.engr.psu.edu/workbooks/formal_report_template.doc' width='80%' height='800px' frameborder='0'></iframe>
A solution adapted from "How do I render a Word document (.doc, .docx) in the browser using JavaScript?".
This is an embedded Microsoft Office document, powered by Office Online.
embed.aspx?src=<your_will_be_your_document_file_url>' width='80%'
add your document file ur here <your_will_be_your_document_file_url>

Getting an Error-404 from my web-host provider. Website converts YouTube to mp3

I am trying to re-create a tutorial I found which converts YouTube to mp3. The problem is when I use the website I get sent to a Error-404 page. I made my website using Freednom to get a free domain name and AwardSpace to get a web-hosting service. My websites name is Simplemp3.ga. When I post the video link I want to convert I get transferred to an Error-404 page. Not sure if it has something to do with the domain name service or the web-hosting service (since they are both free). Maybe there is some limitations preventing the download of YouTube to mp3 with the limited servers and databases?
The way I tried changing the code was from Local host 4000 to the website itself: simplemp3.ga. At first I got a hosting problem when it was directed to my localhost 4000. Then I changed it to simplemp3.ga and I got the Error-404 page from AwardSpace.
Here is the code I changed (JavaScript):
var convertBtn = document.querySelector('.convert-button');
var URLinput = document.querySelector('.URL-input');
convertBtn.addEventListener('click', () => {
console.log(`URL: ${URLinput.value}`);
sendURL(URLinput.value);
});
function sendURL(URL) {
fetch(`http://localhost:4000/download?URL=${URL}`, {
method:'GET'
}).then(res => res.json())
.then(json => console.log(json));
}
To:
var convertBtn = document.querySelector('.convert-button');
var URLinput = document.querySelector('.URL-input');
convertBtn.addEventListener('click', () => {
console.log(`URL: ${URLinput.value}`);
sendURL(URLinput.value);
});
function sendURL(URL) {
window.location.href = `simplemp3.ga/download?URL=${URL}`;
}
After this point I got the Error-404 page from AwardSpace.
Here is the complete code tutorial:
https://blog.usejournal.com/how-i-made-my-own-youtube-downloader-using-javascript-and-node-js-160b172f6e10
Please, any and all help are greatly appreciated!
Thank you

How do I use a downloaded svg file within my application using Tizen Web studio?

I can get an SVG file downloaded, additionally, I can display svg files as you would normally within an image tag. I do not know how to access the folder location for downloads or the wgt-private folder so I may download images to a client's watch and then use the downloaded version.
I'm sure my file is downloading as I've console logged on successful download and when I list the items in the directory the file shows up.
Placing downloads/[filename] or wgt-private/[filename] does not appear to work as these are virtual file locations however I've no idea how to access these files within the application without using the filesystem methods.
Download:
var download_obj = new tizen.DownloadRequest('someFile.svg', 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
onprogress: function(id, receivedSize, totalSize) {
console.log(id);
console.log(receivedSize);
console.log(totalSize);
},
onpaused: function(id) {
console.log(id);
},
oncanceled: function(id) {
console.log(id);
},
oncompleted: function(id, fullPath) {
console.log(id);
console.log(fullPath);
},
onfailed: function(id, error) {
console.log(id);
console.log(JSON.stringify(error));
}
});
Full path comes out as: wgt-private/someFile.svg
Doesn't display as displays a file error in the console on all attempts.
I understand that your questions relates to how to show the image downloaded with tizen.download API in html img tag.
I can see two workarounds that could help you with it:
You can use filesystem API (which you would like to avoid), BUT since 5.0 there is a method which needs no additional privileges and I hope it will match your needs - FileSystemManager.toURI(). It just gets the path to file (returned by download API) and returns the full URI, able to be used in img.
I noticed that download to non-public directories on the device, download API returns the 'hidden' path which uses virtual root, but when downloading to public directory as 'downloads', the full path is returned and it works for img as well.
If both of above is not acceptable for you, I am afraid that the only alternative is to use regular tizen.filesystem API and resolve the path from download API and then use File.toURI() function to get the path.
var link = "http://techslides.com/demos/samples/sample.jpg"
var download_obj = new tizen.DownloadRequest(link, 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
oncompleted: function(id, fullPath) {
console.log("completed " + id + " : " + fullPath);
tizen.filesystem.resolve(fullPath, (s)=>{console.log("Resovled full path: " + s.toURI())}, (e) => {console.log(e)})
},
onfailed: function(id, error) {
console.log("failed " + id);
console.log(JSON.stringify(error));
}
});
You can find the proper web sample app: new Tizen project - Sample - Mobile 4.0 - Web application - Content - Download Manager
Open index.html and replace https://www.sample-videos.com/video/mkv/720/big_buck_bunny_720p_10mb.mkv with your file address.

Share image plus text via Whatsapp with React Native

I am working on a react native app and one of my needs is to be able to share via Whatsapp, a png image (created from a svg) plus some text in the message. I have achieved this on Android using react-native-share but when I try it on iOS, the message is populated with the provided text but the image is ignored. I have also tried with Share from react-native but the result is the same.
I have tried this sharing directly a base64 image (data:image/png;base64,image_data) as well as saving the created image and add the path as the url but the result is always the same.
The only way to make this work on iOS (with both react-native-share and Share) is to omit the message, but the text is needed in the requirement.
Is there a way to achieve this?
Versions:
React Native - 0.55.0
react-native-share - 1.1.2
As a side note, the sharing process on Twitter, Email, SMS and some other apps is working correctly.
Code sample:
const base64Data = this.state.uri
const dir = `${RNFS.DocumentDirectoryPath}/tmp_${moment().valueOf()}.png`
RNFS.writeFile(dir, base64Data, 'base64').then(async () => {
const options = {
url: Platform.OS === 'android' ? `file://${dir}` : dir,
message: '' // By omitting the message, whatsapp shows the image
}
try {
await Share.open(options)
// Delete file when share action is completed
await RNFS.unlink(dir)
} catch (error) {
console.log('error', error)
}
}).catch((err) => {
console.log(err.message)
})

Calling shared drive folder using javascript

I have two servers: A and B.
My Classic ASP application is deployed on Server A.
Server B contains a Folder (ScannedDocuments). I have created a Shared Drive on Server A to point to this folder. The Share Drive is named Q:.
On IE 7, when I try to access file using javascript, I am using:
window.open(file://Q:/a.txt)
It opens the file. But on IE 8 and above and all versions of Firefox, it is not opening. Neither an error is generated nor the file is opening.
I guess it is getting blocked by browser's security features.
Please let me know how I can open files on these browser versions.
Is there any other way to open a remote file using javascript or using IIS?
** Edited **
I tried creating a Virtual Directory on IIS and pointing to Shared Drive. But it gives error: resource or directory not found.
I am using IIS 7
#Anant Dabhi is right - create simple Ajax call to server ant return file content.
Client (JS). Use it instead of window.open(file://Q:/a.txt)
function getFile(filename) {
$.ajax({
url: "/YourWeb/File/Get",
data: {
filename: filename
},
success: function (data) {
console.log(data);
}
});
}
Your "backend". Assume that your are using .NET :)
public ActionResult Get()
{
string pathToFolder = "x:\\yyy\\zzz";
// Strip any directories and leave only name of file. Exception is possible ;)
string filename = Path.GetFileName(Request["filename"]);
byte[] ba = File.ReadAllBytes(Path.Combine(pathToFolder, filename));
string s = Encoding.UTF8.GetString(ba);
// Return as text (if you are absolutetlly sure it is text!)
return Content(s);
// Or pack it in JSON object to have status
return Json(new { Status = true, Data = s });
}
You could connect to UNC if you wish https://msdn.microsoft.com/en-us/library/windows/desktop/aa385482%28v=vs.85%29.aspx

Categories

Resources