Understanding how to use Node.JS fetch [duplicate] - javascript

This question already has answers here:
How do I load an HTML page in a div using JavaScript?
(17 answers)
Closed 2 years ago.
I am getting my hands on Node.JS fetch to understand how it works and then use it.
I have installed node-fetch and followed some tutorials and saw some videos on the subject, but it is not yet all clear. Even if what is shown works, I still have questions. Here one I need to solve soon. What is the way to simply display the page in the browser?
For example in the code below, I use a fetch to access my site (https://mynicewebsite.example.com), possibly setting some options (headers ....), and then I can log a number of informations using console.log(). But how should I change the code if I simply want the contents of the site (https://mynicewebsite.example.com) to be displayed in the browser?
Just as if I had typed the address directly in the address area of the browser.
Here the code with the fetch call.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
const makeFetchCall = async () => {
const response = await fetch('https://mynicewebsite.com', {
method: 'GET',
headers: {
'Authorization': 'Bearer blahfblahdblahzblah',
//..... // possibly some other things
}
});
}
makeFetchCall();
</script>
</body>
</html>

fetch is an API used to get some data from a URL and make it available to JavaScript. It is provided by browsers to JS running in webpages.
node-fetch is a library that makes that API available to Node.js.
There's no sign of Node.js anywhere in your code. You are using the browser version, not node-fetch.
If you want to display a page in the browser, don't use fetch. Navigate to it:
location = "http://example.com"

Related

Firefox extension: cant use variables or functions from element movie_player on ytmusic [duplicate]

This question already has an answer here:
How to use youtube API in firefox extension?
(1 answer)
Closed 5 months ago.
i want to code a firefox extension where i can invite people to a "Yt-Music party" and it will sync up to the host YtMusic.
The element "movie_player" contains a lot of functions and variable which could be usefull, like the current time of the song.
For some reason the getCurrentTime() function works in the webconsole, but not when i have it like this, in my extension.
Do i need extra permission to do this?
Thanks in advance
const ytPlayer = document.getElementById('movie_player')
const test = ytPlayer.getCurrentTime()
console.log(test)
Extensions don't have direct access to elements on the page. You'd have to inject a content script, and then pass data (via messaging) between the page and the extension's background script (or service worker) to have this type of communication. Note also that content scripts don't get access to things like ytPlayer by default either.

How to check if link to image is not broken [duplicate]

This question already has answers here:
Check if image exists on server using JavaScript?
(18 answers)
Closed 2 years ago.
Is there way to check if link to image is working before adding src attribute to image?
What I have tried:
First idea was to make ajax call to image src but I cannot be sure that CORS pocily will allow it.
Adding onError callback into my component. No luck because I use SSR and it causes problems
My use case:
I'm building text editor and user can insert link to image. I want to know if link is ok before inserting it into my model.
The other answers/question aren't specifically about cross-domain requests. If you only have to support modern browsers you can use an opaque fetch request which works cross domain and is pretty easy to use.
fetch('http://example.com/your-image-url', { mode: 'no-cors' }).then(() => {
if (response.ok) {
// the image exists
}
});

Cross-Origin resources sharing when i dont have access to the server [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 4 years ago.
I've been trying to workout if it's possible for me to get rid of my 'Access-Control-Allow-Origin' error.
I'm requesting data from some reports that come back as CSV files but for them to work i have to use a chrome plug in that disables CORS.
after reading tons of stack over flow questions and lots of googling i still can't tell whether it's something I'm not putting in my code or if it's a setting where the data is stored that needs to turn it on.
here is my code that requests the data, bare in mind this works just only with the plug in and my API key has been removed.
function Getfueltype(){
j=JSON.stringify
$.ajax({
url: 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=CSV',
async: false,
success: function (csvd) {
data = $.csv.toArrays(csvd);
},
dataType: "text",
complete: function () {
while (n < (data.length)-2) {
fueltype = j( data[n].slice(1,2));
GigaWatt = j(parseFloat(data[n].slice(2,3)));
arr.push(fueltype);
arr2.push(GigaWatt);
n++
}
drawChart2(data);
}
});
}
If you are attempting this on a local machine to test the code before it goes live on a server, I used --allow-file-access-from-files flag for my chrome.
This allows you to bypass No Access-Control-Allow-Origin header problem.
Example:
Create a copy of chrome.exe in the installation folder.
Send that copy to the desktop as a shortcut.
Right-click on Chrome shortcut and paste the flag at the end of the Target box. (See example string below)
Target - "C:\Users\SuperCoolUser\AppData\Local\Google\Chrome\Application\chrome-copy.exe" --allow-file-access-from-files
Hope that helped even the slightest bit.

HTTP Get request from Angular JS receives empty reply

Since I am fairly new to web development, this might very well be a very easy to solve question. Unfortunately I am not able to solve this myself as I have no clue on where to search.
Currently I'm trying to get data out of an ASP.NET Web API that is running on my local machine. To get this data I've written a small piece of JavaScript using AngularJS:
function MainController($scope, $http) {
$http.get("http://localhost/DBLayerDLL/api/tablets/1005").
then(function(response) {$scope.data=response;},
function(response){$scope.data=response;});
}
The HTML page that is used, is also very simple:
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="scripts/main.js"></script>
</head>
<body ng-controller="MainController">
<h1>Hello World!</h1>
<div>
<div>Data: {{data}}</div>
</div>
</body>
</html>
The action of the controller in my Web API is implemented as follows:
[RoutePrefix("api/tablets")]
public class TabletsController : ApiController
{
[Route("{ID}")]
[HttpGet]
public TabletRecord GetTablet(int ID)
{
TabletRecord tablet = new TabletRecord();
tablet.LoadFromID(ID);
return tablet;
}
}
The problem lies within the response I get from the HTTP request. When printed on the page it looks like this:
{"data":"","status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/DBLayerDLL/api/tablets/1005","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}
Which is not correct, as I know that my API will return data. It gets even weirder for me when I use Fiddler to see what is going on. Within Fiddler I can see the request and see that the response is completely different from what I see on my web page:
Due to my lack of knowledge and experience I don't know what is going on...
Is there any thing I am doing wrong in my JavaScript?
Should I do something else within the HTML page?
Or is there any special thing that I need in my Web API?
Any help or thoughts are highly appreciated!
After spending quite some more time on this I've found a couple of things were needed to solve my problem:
I've noticed that I had to enable CORS on my Web API in order for the JavaScript to be able to make requests to my Web API. I've came to this via this link, I just followed the steps as explained to get it up and running.
I've also discovered at first that I can also get my data using the general XMLHttpRequest object available in JavaScript. By first getting my data to display using this method, I've also discovered the next item:
The response object returned by the $http.get method is actually the object that is directly returned by my Web API. So I can just use the defined properties to display the required data.
On normal php i get the angular variables with
$data = file_get_contents("php://input");
you should look if
print_r($data);
contains what u need.

How to use javascript libraries to make AJAX calls in Facebook Canvas app?

I am writing a Facebook canvas app that needs to make some AJAX calls after a user sends app requests to friends. However, every time I load a javascript library to help with the AJAX calls, it causes the Facebook Javascript SDK to stop working.
I'm loading the Javascript SDK just after the tag as instructed in Facebook documentation.
When users click a button to send a request to a friend, it calls a function like this:
function sendrequest() {
FB.ui({method: 'apprequests',
message: 'Play this game!',
max_recipients: 1,
},
function(response) {
var to = response.to;
var requestid = response.request;
//here I want to send these to a PHP page
//via AJAX for processing
});
}
I started with jQuery loaded between <head> and </head>, but suddenly the FB.ui function that sends app requests stopped working. The console says that the sendrequest() function is undefined.
Another question on StackOverflow suggested using the PHPLiveX, which was working for the person who had asked that question. However, loading this javascript creates the exact same problem. If the page loads any javascript library other than just the Facebook javascript SDK, then the SDK stops working.
Any thoughts on what could cause this? I realize I can use XMLHttpRequest but I hoped to use a library to save time on lots of AJAX calls.
I discovered my problem. I included jQuery by typing the code from scratch, and temporarily forgot that script tags cannot be self-closing:
<script src="jquery.min.js" />
did not work. But
<script src="jquery.min.js"></script>
works fine.

Categories

Resources