I'm playing around with Deno but I can't find the standard HTTP client.
I also googled "deno http client" which gives me https://deno.land/x/std/http/client/, but the link is broken. Something was indexed by Google and later removed from the repo.
404 - Not Found
This file or directory could not be found.
I found 3rd party libraries soxa and deno-http but I am looking for something standard.
Is there a standard HTTP client for Deno that I am missing?
deno implements a variety of Web APIs. To make an HTTP request in deno you use fetch.
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await res.json();
Web APIs are exposed to the global scope the same way they're in the browser. deno aims to be browser compatible whenever it's possible.
You'll also be able to use:
FormData
Headers
cache (.put & .match supported)
Related
I'm trying to integrate the Zoom Web Video SDK into an existing web application, and SharedArrayBuffer has become a requirement for performance reasons, and in order to enable it the site has to implement Cross Origin Isolation. I've gone ahead and added the requisite configuration to NGINX, namely:
add_header 'Cross-Origin-Embedder-Policy' 'require-corp';
add_header 'Cross-Origin-Opener-Policy' 'same-origin';
... but of course this has knock-on effects for the rest of the previously existing and working site. The Google APIs won't seem to load successfully anymore.
I changed my index.html to add the crossorigin attribute to the Google API script tag as follows:
<script src="https://apis.google.com/js/platform.js" async defer crossorigin></script>
... and in my javascript source code I have (paraphrasing and reducing complexity to get the the point):
gapi.load('client:auth2', function() {
gapi.client
.init({
client_id: 'MY-CLIENT-ID',
cookiepolicy: 'single_host_origin',
discoveryDocs: ['https://classroom.googleapis.com/$discovery/rest?version=v1'],
scope: 'profile email'
})
.then(() => console.log('init finished'))
.catch(e) => console.error('init failed', e));
});
In that code, gapi and gapi.client are well-defined, but the init call never completes (no console logs from the then or from the catch). Looking at the network tab in devtools shows a failed GET request to:
https://content-classroom.googleapis.com/static/proxy.html?usegapi=1& ... and bunch of other stuff i'm not sure if is sensitive so am omitting
When you dive into the response, it shows:
To use this resource from a different origin, the server needs to
specify a cross-origin resource policy in the response headers:
Cross-Origin-Resource-Policy: same-siteChoose this option if the resource and the document are served from the same site.
Cross-Origin-Resource-Policy: cross-originOnly choose this option if an arbitrary website including this resource does not impose a
security risk.
Obviously, I can't control what Google's servers do, but can anyone instruct me as to how I can get this to work correctly. This only goes awry in the presence of my NGINX configuration change at the start of this post.
Update
I partially worked around this by fetching the discovery document for the API separately and passing the result into the gapi.client.init method instead of the URL. However, while I don't get the aforementioned outcome in the network tab of devtools anymore, but I instead get weird / inconsistent results with responses like "popup_closed_by_user" and "popup_closed_by_browser" happening in response to my GoogleAuth.signIn call. If I remove the headers from NGINX it starts behaving as expected again. I don't understand what's going on with this.
I am creating a REST API in Go, and I want to build URLs to other resources in my replies.
Based on the http.Response I can get the Host and URL.
However, how would I go about getting the transport scheme used by the server? http or https?
I attemped to check if server.TLSConfig is nil and then assuming it is using http since it says this in the documentation for http.Server:
TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS
But it turns out this exists even when I do not run the server with ListenAndServeTLS.
Or is this way of building my URLs the wrong way of doing things? Is there some other normal way of doing this?
My preferred solution when running http and https is just to run a simple listener on :80 that redirects all traffic to https. Then any real traffic can be assumed to be https.
Alternately I believe you can access a request's URL at req.URL.Scheme to see the protocol.
Or do you mean for the entire application? If you accept configuration to switch between http and https, then can't you look at that and see which they chose? I guess I'm missing some context maybe.
It is also common practice for apps to take a baseURL via flag or config to generate external urls with.
I'm currently building an ASP.NET web application to simplify the provisioning of Google Sites, pages, Gadgets on Google Sites and ACLs for Google Sites.
I have encountered the issue which many a developer has already come across: cross-origin resources. According to the Google documentation on CORS requests to Google APIs, you simply use an XMLHttpRequest (or AJAX) request, providing your access token in the header. More information can be found here:
https://developers.google.com/api-client-library/javascript/features/cors
I've been perfectly able to accomplish this when I'm accessing the Google Sites API from within my domain on Google Sites, injecting AJAX requests while my browser window's location is within the domain. An example of a succeeded request to make a new site from within my domain:
$.ajax(
{
////// REQUEST \\\\\\
type: "POST",
url: "https://sites.google.com/feeds/site/[domainName]",
contentType: "application/atom+xml",
headers: {
"Authorization": "Bearer " + [accessToken],
"GData-Version": "1.4"
},
data: ["<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'>",
"<title>What a site</title>",
"<summary>Best description ever.</summary>",
"<sites:theme>ski</sites:theme>",
"</entry>"].join(""),
////// LOGGING \\\\\\
beforeSend: function () {
console.log('-------Making-the-request-------');
},
success: function (result) {
console.log(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
console.log(xhr.status);
}
});
(In several cases below, I'm writing https:// as [https] due to my account still being restricted to 2 links in a post).
At this point everything was going great, I thought I had everything set to use the code into my ASP.NET site. Alas, things don't always go to plan. When I executed the exact same AJAX call from within my application (right now still hosted on [https]localhost:44301), I get the following error:
XMLHttpRequest cannot load
[https]sites.google.com/feeds/site/[censored] Response to preflight
request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '[https]localhost:44301' is therefore not allowed
access. The response had HTTP status code 405.
The usual CORS error. I was surprised though, as the advised way of making requests to Google APIs is exactly that. I've also found an article about using CORS with the Google Cloud API:
https://cloud.google.com/storage/docs/cross-origin
In the article it states:
Most clients (such as browsers) use the XMLHttpRequest object to make
a cross-domain request. XMLHttpRequest takes care of all the work of
inserting the right headers and handling the CORS interaction with the
server. This means you don't add any new code to take advantage of
CORS support, it will simply work as expected for Google Cloud Storage
buckets configured for CORS.
Of course, this isn't the Google Sites API, but I find it hard to believe that Google hasn't implemented the same functionality in all of their APIs.
Does anyone know whether it's possible to achieve successful requests such as this from within a standalone ASP.NET application? And if so, how?
Many thanks for spending time to read about my hardships.
UPDATE:
I've contacted Google Apps Support regarding my issue, and have gotten the following response:
In addition to the information you provided, I also reviewed your post
at
CORS authenticated requests to Google Sites feed/API blocked.
The note at
https://developers.google.com/google-apps/sites/docs/1.0/developers_guide_java#SiteFeedPOST
only reinforces the statement under 'Can I create a new Google Site?'
and 'How do I copy a site?' at
https://developers.google.com/google-apps/sites/faq#Getting__Started,
which states 'Google Apps users can use the site feed to ...' However,
I don't see why this is relevant to your issue, if you've authorised
against your domain administrator account, as the note is only
indicating that gmail.com users won't be able to use the listed
methods to create, or copy a site.
I haven't used CORS, so can't comment on it's operation, but have been
able to successfully list, and create sites using HTTP GET and POST
requests via a raw HTTP client, so the API is operating as it should
with regard to cross domain requests. I used the sample XML document
at
https://developers.google.com/google-apps/sites/docs/1.0/developers_guide_protocol#SitesFeedPOST
to create my site, configuring the client with credentials for my
Developer console project. The fact that the request only fails in
your ASP.NET site implies that there is something in that environment
which isn't configured correctly. Unfortunately that's outside my
scope of support, so I'm unable to provide any specific advice, other
than to check the relevant documentation, or post a request in the
ASP.NET section of Stack Overflow at
https://stackoverflow.com/questions/tagged/asp.net.
Could you try again after removing "GData-Version": "1.4"?
If you really want to send this value, send it by adding a query parameter such as v=X.0. Resource from here
UPDATED:
"Note: This feature is only available to Google Apps domains." From guides
SOLVED
It seems that a lot of browsers would still block an AJAX request across different domains, even when it's allowed by the API you're trying to reach. Instead of using AJAX, I'm now using the C# WebRequest in a DLL.
Example:
// Create the request
WebRequest request = WebRequest.Create("https://sites.google.com/feeds/site/[domainName]");
request.Method = "POST";
request.contentType = "application/atom+xml";
request.Headers.Set(HttpRequestHeader.Authorization, "Bearer " + [accessToken]);
request.Headers["GData-Version"] = "1.4";
// Fill in the data and encode for the datastream
string data = ["<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'>",
"<title>What a site</title>",
"<summary>Best description ever.</summary>",
"<sites:theme>ski</sites:theme>",
"</entry>"].join("");
byte[] byteArray = Encoding.UTF8.GetBytes (data);
// Add the data to the request
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
// Make the request and get the response
WebResponse response = request.GetResponse ();
More info can be found on MSDN:
https://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx
My meteor server will fetch data from another source on Internet. The request has to go via a proxy. How can I specify the proxy server for server-side HTTP.call's?
You could easily make all HTTP.* calls through a proxy if only Meteor developers accepted my pull request to pass through options like proxy to the request module, on which the HTTP package is based.
Please comment on this GitHub issue to ask for that.
UPDATE: Since the Meteor devs refused to implement that change, I published an Atmosphere package that lets you transmit to Node (i.e. to the request module) any options you want.
Check out http-more on Atmosphere.
Found a solution for my problem.
I'm using Windows and could not find a way to set a default proxy for the OS as Serkan mentioned. Setting proxy server in Internet Explorer internet options LAN settings did not work. Settings proxy in winHTTP did not work. Anyone else know how to do it?
The most reasonable would be that Node read a environment variable and used that. So, I created an environment variable "HTTP_PROXY" and to see if node would read it I tried:
D:\Appl\.meteor\tools\a5dc07c9ab\bin>node -e "console.log(process.env.http_proxy)"
and it did output my variable. But, when trying to make a http.get() request directly within Node it failed. Node is obviously not using that variable ...
The conclusion of that is that I have to explicitly set the proxy in my app, but that is not possible with Meteor HTTP. Instead I could use the request module (that Meteor HTTP is using) and set the proxy. Not the ideal solution, because my app has to know about the proxy, but ok for my purpose.
if (Meteor.isServer) {
var request = Npm.require("request");
var makeRequest = Meteor._wrapAsync(thirdLibMakeRequest);
function thirdLibMakeRequest(options, callback) {
options.proxy = "http://myProxyServer:8080";
request(options, callback);
};
var response = makeRequest({ url: "http://UrlToSomeSite" });
}
Include the request module
Wrap the 3rd-lib async method so we can use it in Meteor
set the proxy property of the request module
use makeRequest to make requests.
Since the platform your meteor app will be running on will be behind the proxy as a whole, you'll be needing proxy access generally anyway.
Therefore, you can set your platform (os) up to connect to the proxy server by default, therefore Meteor will not necessarily know/care about the presence of a proxy since it will be transparent to it.
I write a bunch of scripts in javascript and want to switch to dart or at least start using it. I do have one question though: i know js doesn't support x-domain requests in the browser, but what about running a dart application/script from the server, is it still the same? can this even be done?
basically, since i have no access to the web server to which i query, cross domain ability is a big necessity.
It sounds like you might be asking about writing a server side command line script which can make requests to an HTTP server. Though the wording of question isn't totally clear to me. (The answers above are about browser based Dart scripts.)
This is possible with Dart. There are no cross origin restrictions in this case.
See the HttpClient class.
Or you can use the http package on pub.
I recommend using the http package, as it provides a simpler high-level interface.
Here is an example using the http package:
import 'dart:io';
import 'package:http/http.dart' as http;
main() {
http.read("http://google.com").then((content) {
print(content);
});
}
You'll need to update your pubspec.yaml file to add the following dependencies:
name: Http Example
dependencies:
http: any
pathos: any
(Actually, you should only need to include http, but I think the http package is missing the pathos dependency in it's pubspec.yaml file.)
I couldn't find the pretty documentation for http, but there is some doc comments in the source file.
Cross domain security is built into the browser, so is neither a feature of Dart or JavaScript.
Useful for testing: you can pass flags into chrome that will disable this security feature. See here: http://joshuamcginnis.com/2011/02/28/how-to-disable-same-origin-policy-in-chrome/
If you want to do a GET request, then you can use Dart JavaScript interop, see this section in this article: http://www.dartlang.org/articles/json-web-service/#note-on-cors
If you want to POST requests on the other hand, you'll run into problems unless the target server supports CORS. More details here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Edit: The correct approach would be to have your client-side code communicate with a server you own, and have that server communicate with the third-party server.
You can enable cross-origin requests on the server by setting the Access-Control-Allow-Origin header on the http response. The value is either * to allow any origin to access the resource, but it is definitely safer to specify valid origins.