I am trying to build an interface that communicates with a REST API for attask.com. Their API is convenient because it returns JSON. I thought that was perfect because I could forget about server-side C# code and just write the interface using jQuery and AJAX. However, when I try to make an AJAX request to their API I get an error in Chrome's javascript console:
Origin http://mysite.com is not allowed by Access-Control-Allow-Origin.
What does this mean? Is this the browser preventing the request? If so, why?
Update:
If I don't have any control over the server and it does not respond to JSONP requests, is my only option to employ a server-side REST client and have my AJAX talk to my own domain instead of attempting to go cross-domain?
I found that jQuery-JSONP is the easiest way to do this.
jQuery JSONP is an alternative solution to jQuery's implementation of JSONP
jQuery-JSONP features:
error recovery in case of network failure or ill-formed JSON responses,
precise control over callback naming and how it is transmitted in
the URL,
multiple requests with the same callback name running concurrently,
two caching mechanisms (browser-based and page based),
the possibility to manually abort the request just like any other AJAX request,
a timeout mechanism.
Sample Code to Get user profiles from YouTube
function getProfile(userId) {
$.jsonp({
"url": "http://gdata.youtube.com/feeds/api/users/"+userId+"?callback=?",
"data": {
"alt": "json-in-script"
},
"success": function(userProfile) {
// handle user profile here
},
"error": function(d,msg) {
alert("Could not find user "+userId);
}
});
}
For more samples.
Alternatively, you can use the fututre standard Cross Origin Resource Sharing that is supported on modern browsers and fallback to JSONP for the other browsers.
You'll want to use JSONP, JQuery has nice support for this built in. See JQuery Documentation for more info.
You need to make a JSONP request to perform a cross domain AJAX request, you can do this by appending
callback=?
To the URL you send the request to
Related
I'm trying to bypass the hCaptcha in Discord Account Registration using selenium webDriver in C#. I'm using CapMonster Cloud API for solving the captcha itself and as response I'm getting bypass token.
The problem that I currently have is that I can't locate the callback function that I need to call/submit, in order to pass the hCaptcha.
I'm setting the bypass token into "g-recaptcha-response" and "h-captcha-response" textareas, but can't find a way to locate and call the callback function. There is no form to be submitted.
using selenium webDriver in C#
10/10 Would recommend doing discord captcha bypasses using:
PuppeteerExtraSharp/ExtraStealth
(as selenium has some obvious tracers)
Puppeteer has a lot more freedom in it's API as well as the fact that 2capthca is a much more popular method for solving h-captchas
I know this doesn't answer your question but i hope you look into this as a potential better alternative if you do not receive a more traditional answer.
You can do that with Anti-Captcha.com plugin which will do the job automatically. It injects its own callbacks, so when a token is ready it submits the form. If you ever have problems with plugin, support guys here will help you out.
Web communication has to happen in one of the methods defined on this page
So if anything is being sent and received from a server to the browser it has to be one among those methods. Generally the most common methods are POST and GET.
The statement "There is no form to be submitted" is somewhat confusing. A form is just display of fields to collect data from a user. In case a website does not need user input they do not show the form. They would instead capture the required data and send a POST request to the server (without the user ever noticing), in a manner similar to how a form would have sent the data. This is a normal behavior for almost all major websites. An example is google-analytics codes.
So what you need to look for is a POST request (mostly or PUT maybe GET - depends) where the data you are targeting is received or sent.
In your case there indeed is a form which displays the captcha (that is how you see it) and and associated POST request which does what you need.
Url for the post request on the captcha is POST /getcaptcha?s=xxxxxxxx-xxxe-xxxx-xxxx-xxxxxxxxxxxx HTTP/3
Url where it is sent is POST /api/v9/auth/register HTTP/3
These basics apply to any web communication and not just the website in question.
Using HTTP I want to send simple string data through android to a C# .NET server. This link suggests using OKHTTP which looks great, but I'm not sure how this would talk to a C# server as I will need a 'connection' where I can send data back to the android phone.
OKHTTP seems to manage drops in connection elegantly according to the website, which is fantastic because I need this kind of persistance, but I'm not sure how I would implement the C# side.
Does anyone know a method of accomplishing this?
It sounds as though you want to do a normal HTTP POST to your server. It's the same thing that would happen when you fill out a form on a web-page and submit the data to a server. If it's a normal kind of webserver it should have full support for receiving a POST and returning a response as well. Are you writing the .NET web service as well?
As for client side technology to use: OkHTTP is a greaty drop-in class for making HTTP requests to a server, but if you plan to do many of them you should also look into wrapping the actual HTTP client into an API that takes care of asynchronous callbacks and things like that. You don't want to be doing HTTP requests on the UI thread and it's boring and error prone to wrap all such calls in AsyncTasks or similar. Take a look at AndroidAsyncHttpClient:
"An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing."
(As a sidenote AndroidAsyncHttpClient might get support for using OkHTTP instead of the default Apache HttpClient)
POSTing to a server is as simple as this:
RequestParams params = new RequestParams();
params.put("A_KEY_TO_IDENTIFY_YOUR_STRING", "THE_STRING_YOU_WANT_TO_SEND");
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.yourserver.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// handle your response from the server here
System.out.println(response);
}
});
I have a Web API written in ASP.NET that I'm consuming via AngularJS $http.
I have enabled caching in my AngularJS factory as follows but every request still returns a response of 200, never 200 (from cache) or 304 (and by every request I mean making the same web api request numerous times on the same page, revisiting a page I've already visited that contains a Web API request, refreshing said page etc).
angular.module('mapModule')
.factory('GoogleMapService', ['$http', function ($http) {
var googleMapService = {
getTags: function () {
// $http returns a promise, which has a 'then' function, which also returns a promise
return $http({ cache: true, dataType: 'json', url: '/api/map/GetTags', method: 'GET', data: '' })
.then(function (response) {
return response.data;
});
};
return googleMapService;
}]);
Am I missing something from the AngularJS side of things? Or is this a Web API problem. Or both?
Turns out it was a Web API thing. I'd overlooked the fact that the response header clearly stated that caching was disabled.
Response as viewed in the Network tab of Google Chrome:
Upon further investigation (and as seen in the image above), caching is disabled in Web API controllers. Even the [OutputCache] attribute, which is used in regular MVC controllers, isn't supported.
Luckily I found this blog:
http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
which lead me to these two solutions:
ASP.NET Web API CacheOutput
CacheCow
I decided to go with CacheOutput as it lets me use attributes like:
[CacheOutputUntilToday] which supports server & client side caching.
Or if I wanted to just use client-side caching I can use something like:
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]
Which seemed a little easier at first glance that CacheCow's approach. And easier to refactor out later if need be.
Now additional requests give me a 200 (from cache):
With a refresh giving me a 304 Not Modified:
Problem solved! Hope this helps someone else.
Similar questions have been asked about the nature of when to use POST and when to use GET in an AJAX request
Here:
What are the advantages of using a GET request over a POST request?
and here: GET vs. POST ajax requests: When and how to use either?
However, I want to make it clear that that is not exactly what I am asking. I get idempotence, sensitive data, the ability for browsers to be able to try again in the event of an error, and the ability for the browser to be able to cache query string data.
My real scenario is such that I want to prevent my users from being able to simply enter in the URL to my "Compute.cshtml" file (i.e. the file on the server that my jQuery $.ajax function posts to).
I am in a WebMatrix C#.net web-pages environment and I have tried to precede the file name with an underscore (_), but apparently an AJAX request falls under the same criteria that this underscore was designed to prevent the display of and it, of course, breaks the request.
So if I use POST I can simply use this logic:
if (!IsPost) //if this is not a post...
{
Response.Redirect("~/") //...redirect back to home page.
}
If I use GET, I suppose I can send additional data like a string containing the value "AccessGranted" and check it on the other side to see if it equals this value and redirect if not, but this could be easily duplicated through typing in the address bar (not that the data is sensitive on the other side, but...).
Anyway, I suppose I am asking if it is okay to always use POST to handle this logic or what the appropriate way to handle my situation is in regards to using GET or POST with AJAX in a WebMatrix C#.net web-pages environment.
My advice is, don't try to stop them. It's harmless.
You won't have direct links to it, so it won't really come up. (You might want your robots.txt to exclude the whole /api directory, for Google's sake).
It is data they have access to anyway (otherwise you need server-side trimming), so you can't be exposing anything dangerous or sensitive.
The advantages in using GETs for GET-like requests are many, as you linked to (caching, semantics, etc)
So what's the harm in having that url be accessible via direct browser entry? They can POST directly too, if they're crafty enough, using Fiddler "compose" for example. And having the GETs be accessible via url is useful for debugging.
EDIT: See sites like http://www.robotstxt.org/orig.html for lots of details, but a robots.txt that excluded search engines from your web services directory called /api would look like this:
User-agent: *
Disallow: /api/
Similar to IsPost, you can use IsAjax to determine whether the request was initiated by the XmlHttpRequest object in most browsers.
if(!IsAjax){
Response.Redirect("~/WhatDoYouThinkYoureDoing.cshtml");
}
It checks the request to see if it has an X-Requested-With header with the value of XmlHttpRequest, or if there is an item in the Request object with the key X-Requested-With that has a value of XmlHttpRequest.
One way to detect a direct AJAX call is to check for the presence of the http_referer header. Directly typed URLs won't generate a referrer, but you still won't be able to differentiate the call from a simple anchor link.
(Just keep in mind that some browsers don't generate the header for XHR requests.)
I'm stuck on a clients host that has medium trust setup which blocks cross domain requests and need data from a 3rd party domain. I now have the option to use JSONP.
I've used JSONP from the client with jQuery to get around the browsers cross domain security and I've used HttpWebRequest in ASP.Net 3.5.
Is it possible to use JSON on the server and if so how?
I don't think it is, but worth asking seeing as I already have this app written server side....
Thanks,
Denis
The easy way might be just to proxy the JSONP request through your server. If that isn't an option (because the data must be processed in some way on the server) you can manually strip off the function-call from the return and then JSON-parse the rest
So if the JSONP call returns:
F001( { "moose" : "sister" } )
First, erase everything up to the first parenthesis and after the last so you have
{ "moose" : "sister" }
And parse that into whatever you need.