Unable to fetch Json file in javascript in Django - javascript

I have a json file that I would like to fetch in javascript and create divs for it in the webpage.
My issue is that I am providing local path of the json file to the fetch method but it is adding it to the django webpage url.
The code below tries to fetch the local path of json file:
fetch('../../scrapers/jsonOutputs/linkedin_jobs.json')
.then(response => response.json())
.then(data => {
const jobListings = data.Jobs;
jobListings.forEach(job => {
const jobTitle = job["Job Title:"];
const employerName = job["Employer name: "];
const jobLocation = job["Job Location: "];
const jobDetails = job["Job Details: "];
const linkToJob = job["Link To Job: "];
const jobListingElement = document.createElement("div");
jobListingElement.classList.add("job-listing");
jobListingElement.innerHTML = `
<h2>${jobTitle}</h2>
<p>${employerName}</p>
<p>${jobLocation}</p>
<div class="job-description-container">
<div class="job-description">
<p>${jobDetails}</p>
View Job
</div>
</div>
`;
const jobListContainer = document.getElementById("job-list-container");
jobListContainer.appendChild(jobListingElement);
});
});
Now when I run the django webapp and inspect element the webpage, I get the following error
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (linkedin_jobs.json, line 0)
[Error] Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.
promiseEmptyOnRejected (jobsearch-func.js:4)
promiseReactionJob
The inspect element shows
http://127.0.0.1:8000/scrapers/jsonOutputs/linkedin_jobs.json
which is problematic since this is not the path to my json file but instead its in my project folder.
How can I read the json file in javascript and create divs?
The code for running my javascript in my html page:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h2 id="job-list-heading">Job Listings</h2>
<div id="job-list-container">
</div>
<script src={% static 'js/jobsearch-func.js' %}></script>
</body>
</html>

Related

Source would taint origin

Why does following code throw “Uncaught (in promise) DOMException: Failed to execute 'detect' on 'BarcodeDetector': Source would taint origin.” when opening file in browser (file:///Users/sunknudsen/Desktop/index.html)?
Might relate to following mentioned in this question… if so, how can one work around limitation?
If any ImageBitmapSource have an effective script origin (origin) which is not the same as the Document’s effective script origin, then reject the Promise with a new DOMException whose name is SecurityError.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BarcodeDetector</title>
</head>
<body>
<h1>See “Console” tab of dev tools…</h1>
<img id="qr" src="https://tails.boum.org/donate/bitcoin-bc1qjg53lww9jrm506dj0g0szmk4pxt6f55x8dncuv.png" />
<script>
const test = async (qr) => {
const barcodeDetector = new BarcodeDetector({ formats: ["qr_code"] })
const detectedBarcodes = await barcodeDetector.detect(qr)
detectedBarcodes.forEach((detectedBarcode) => {
console.log(detectedBarcode.rawValue)
})
// Expected console.log output => bitcoin:bc1qjg53lww9jrm506dj0g0szmk4pxt6f55x8dncuv
}
const qr = document.getElementById("qr")
qr.addEventListener('load', () => {
test(qr)
})
</script>
</body>
</html>

How to import functions or variables from node.js file in AngularJs or Angular?

Hi I am working with IOTA distributed ledger. I have iota client library for node.js.
I want to read data from node.js file where I access IOTA distributed ledgers and pass it to Html where user can see.
My client.js file:
const Iota = require('#iota/core');
const Extract = require('#iota/extract-json');
const iota = Iota.composeAPI({
provider: 'https://nodes.devnet.iota.org:443'
});
let x = [];
iota.getBundlesFromAddresses(['PXMPEGYZCOVEOSRAUXY9VYRBHJBSDWORWQNBDJRVEFTMXZWLTQZSPHEUDMXT9YKGPMMSVDSNHSJNWQUOX'])
.then(bundle => {
for (let i = 0; i < bundle.length; i++) {
console.log(JSON.parse(Extract.extractJson(bundle[i])).message);
x[i]=JSON.parse(Extract.extractJson(bundle[i])).message;
}
})
.catch(err => {
console.error(err);
});
I want to pass x[i] variable to html.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="client">
{{ x[0]}}
{{ x[1]}}
{{ x[2]}}
</div>
<script src="myApp.js"></script>
<script src="client.js"></script>
</body>
</html>
I know how to read data from controller but how am I gonna read data if client.js has imported libraries.
I tried in Angular to convert libraries to typescript but couldnt figure out.
This is typically done in package.json, such as server or build

How do I resolve: "Uncaught ReferenceError: buffer is not defined"

I am attempting to submit a file with an HTML library using the IPFS Api. In order to do so I need to buffer the input before I add the file to IPFS.
My issue is that I have tried every option I've come across on the internet on how to resolve the error "Uncaught ReferenceError: buffer is not defined". I have reinstalled npm, Node, and used browserify with no success.
So what I did is I installed "npm install buffer" and went to the folder where index.js is located and used browserify to attempt to create a standalone buffer.js file.
browserify index.js -o buffer.js
I attempted to include the buffer.js file at the top of my HTML file and it changed the error to "require is not defined."
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript file upload</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="./buffer.js"></script>
<script src="https://unpkg.com/ipfs-api#9.0.0/dist/index.js"
integrity="sha384-5bXRcW9kyxxnSMbOoHzraqa7Z0PQWIao+cgeg327zit1hz5LZCEbIMx/LWKPReuB"
crossorigin="anonymous"></script>
</head>
<script type="text/javascript">
function upload() {
const reader = new FileReader();
const buf = require('buffer');
reader.onloadend = function() {
const ipfs = window.IpfsApi('localhost', 5001) // Connect to IPFS
buf = buffer.Buffer(reader.result) // Convert data into buffer
ipfs.files.add(buf, (err, result) => { // Upload buffer to IPFS
if(err) {
console.error(err)
return
}
let url = `https://127.0.0.1:5001/ipfs/${result[0].hash}`
console.log(`Url --> ${url}`)
document.getElementById("url").innerHTML= url
document.getElementById("url").href= url
document.getElementById("output").src = url
})
}
const photo = document.getElementById("photo");
reader.readAsArrayBuffer(photo.files[0]); // Read Provided File
}
</script>
<body>
<form action="/">
<fieldset>
<legend>Upload photo</legend>
<input type="file" name="photo" id="photo">
<button type="button" onclick="upload()">Upload</button>
</fieldset>
</form>
</br>
</br>
<a id="url"></a>
</br>
</br>
<img id="output">
</body>
</html>
Here is what my project currently looks like:
How can I get the above code to work by recognizing "buffer" with a local HTML file to upload files to IPFS in Windows 10?

Parse Javascript and Cloud Code

I am trying to set up a simple test webpage to execute some cloud code that sends a push notification from Parse. I use back4app.com. Here is what I have so far:
JS:
Parse.initialize('APP_ID');
Parse.serverUrl = 'https://parseapi.back4app.com/';
function sendPushNotification() {
let messageBox = document.getElementById('messageBox');
let messageToPush = messageBox.value;
Parse.Cloud.run("sendPushNotification", { message: messageToPush }).then(function(result) {
console.log("result: " + JSON.stringify(result));
}, function(error) {
console.log("Error: " + JSON.stringify(error));
});
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="https://unpkg.com/parse/dist/parse.min.js"></script>
<script src="main.js"></script>
</head>
<body>
Message to Push:<br>
<input id="messageBox" type="text" /><br>
<input type="button" value="Push" onclick="sendPushNotification()" />
</body>
</html>
But when I add some text to the text box, I get these errors:
[Error] Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “api.parse.com” which could put your confidential information at risk. (sendPushNotification, line 0)
What is going wrong? In the Parse Developers JS Guide, it says:
To initialize your own Parse-Server with Javascript, you should
replace your current initialization code with this
Parse.initialize("YOUR_APP_ID");
Parse.serverURL = 'http://YOUR_PARSE_SERVER:1337/parse'
I used the back4app url that I use in my iOS app. So confused
Please make sure you're following this structure below:
Parse.initialize("YOUR_APP_ID", "YOUR_JAVASCRIPT_KEY");
Parse.serverURL = 'https://parseapi.back4app.com'

Create a file in a standard position to read it in an html page

I want to write a Javascript in a standard location and connect this file to a page html.
Write: (using Swift 1.2)
let path = NSTemporaryDirectory() + "foo.js"
var error: NSError?
text = "12345"
text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
html:
<html>
<head>
<script src="path/foo.js"></script>
</head>
<body>
<p> Use Foo </p>
</body>
Which path i can use?

Categories

Resources