I have a webserver that return response as,
HTTP/1.1 302 Found
message://ActualMessage
This works well for UI Clients such as Android and iOS, but how can I handle this case on a web browser?
For example, a browser request to
GET https://myserver.com HTTP/1.1
And a response looks like,
HTTP/1.1 302 Moved Temporary
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
Unfortunately can't change the server to not return that response. I am not seeing a way to how to get this response from the browser. A native WebView can easily handle that response.
Browser will follow "302 Redirect". There is no way how to intercept it.
However, as a workaround you may try:
use xmlHTTPRequest may work (if server allows, see this answer for possible issues)
iframe may work
Related
As far as i understand all what REST do is standartize a data sended to server by adding some headers. For example REST request can generate a line of bytes like so: POST /qwe HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive and finish it with some user input.
Now im just playing with writing my own JS server and here is my question: is there a way in JS to send some data(bytes) without this REST addings like headers/method and will it work for browsers and HTTP protocol itself?
For example instead of sending POST /qwe HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive MY DATA OVER THERE!!! just send MY DATA OVER THERE!!! so my server can read only user data without everything else.
Iv tried to google and end up that XMLhttpRequest and fetch both require some CRUD method to be specified and adding some headers in request anyway.
HTTP requests:
Need to specify the method
Need to specify the Host as a header (in HTTP 1.1. and newer)
Will include some other request headers automatically when make using JS from a browser
This has nothing to do with REST. It's just how HTTP works.
A non-HTTP protocol could avoid having that. JavaScript in a browser has no mechanisms that allow making non HTTP requests.
You might want to research WebSocket which allows two way communication over a single connection … but that is a bootstrapped by HTTP so doesn't really fulfil your requirement.
For example instead of sending POST /qwe HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive MY DATA OVER THERE!!! just send MY DATA OVER THERE!!! so my server can read only user data without everything else.
I suspect you're misunderstanding what a request is, on a fundamental level. Without POST (the method), /qwe (the path), HTTP/1.1 (the protocol) and 127.0.0.1 (the address) there is no way for your computer to know where and how to send the data. These are necessary if you want to communicate with a server, and removing them will mean your code no longer works.
You're working with very low-level data here, which is probably not what you actually want to be doing. There are some packages which will let you ignore the how and what of the request, and focus on just the data inside it. Express might be a good place to start. You can set up a simple express server to handle requests on specific paths, and reply with data that your frontend can then use.
A REST API is a high-level concept and largely unrelated to what you're asking about.
Medium has an RSS feed available at https://medium.com/feed/[#username]. I'm trying to fetch all my blog posts using an XMLHTTPRequest. When I test on local, I run into CORs errors. When I turn on CORs Chrome extension, I get a 401 error. Any ideas? Has anyone succeeded in calling Medium RSS?
To get https://medium.com/feed/[#username] content using XHR, you can make the XHR request through a proxy of some kind. For example, trying giving your current XHR code this URL:
https://cors-anywhere.herokuapp.com/https://medium.com/feed/#sideshowbarker
That’ll cause the request to go to https://cors-anywhere.herokuapp.com, a open/public CORS proxy which then sends the request on to https://medium.com/feed/#sideshowbarker.
And when that proxy gets the response, it takes it and adds the Access-Control-Allow-Origin response header to it and then passes that back to your requesting frontend code as the response.
That response with the Access-Control-Allow-Origin response header is what the browser sees, so the error message the browser is showing you now goes away, and the browser allows your frontend JavaScript code to access the response.
Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.
The reason you need a proxy is, responses from https://medium.com/feed/[#username] don’t include the Access-Control-Allow-Origin response header, so your browser will refuse to let your frontend JavaScript code access those responses cross-origin.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.
This is a bug.
Bug has opened. (Dan Abramov approved)
I don't know if this is a duplicate post or not, sorry if it is. I'm using jquery.getJSON to load a json on my server which works just fine. Although, if I try and load a json file on a different server it doesn't work. I know I don't have any code here (because there's not much point) but I just want to know if I'm using it wrong or if it isn't supposed to load external files. I'm using the iOS Safari browser if that effects anything.
EDIT: I've looked at the console (idk what the error thing really means, it's just red with an x by the url it's trying to get the json from) and it looks like it's not actually receiving the data. Plus, do remember I'm on iOS, not desktop so I couldn't look at the console in the "Develop tab :P
EDIT 2: Great! I think I got it working! http://skitty.xyz/getJSON/
You're most likely encountering a path issue; the purpose of $.getJSON is to acquire data via http GET request so yes, it is intended to work remotely. To diagnose your issue, make certain you can access the json file in your browser first: http://domain.com/my_data.json. If that works, use that as the URL you pass into $.getJSON:
$.getJSON( 'http://domain.com/my_data.json', function(data) {
// do something with your data
});
http://api.jquery.com/jquery.getjson/
jquery.getJSON uses ajax which is all about external resources. Here's a couple things to check for if it's not working on an external resource:
1: Is the path you specified correct? The usage is jquery.getJSON(path, callback). The path should be something you can just drop in your browser and see. If an incorrect path is your problem, you'll see a 404 in the console.
2: Is the resource http and your site https? Non-secure resources on secure pages will get blocked by browser security features. You'd see a error to this effect in the console.
3: Is CORS (Cross-origin resource sharing) enabled for your site on the external resource? Servers will sometimes use a whitelist of IPs and domains to determine what origins are allowed to make requests of it. You'd also see an error to this effect in the console.
There probably some other things to look for but this is where I'd start.
Also, by all means, use the debugging features of Safari to LQQK at the actual HTTP data-streams that are passing back-and-forth in response to what you're doing. (You might need to click on a preference to see the "Develop" menu, which will take you to "Show Web Inspector" and its Network tab.)
This approach will instantly answer many questions that a JavaScript-centered approach will not so-readily tell you. (And of course, you can look at the JavaScript console too ... and at the same time.) "The actual data streams, please." Safari will tell you "exactly what bytes" your app actually sent to the server, and "exactly what bytes" the server sent in return. "Priceless!™"
Are you saying you are using jquery ajax request to load some json data from a server?
check the "not working server" has the same end point as your server.
Check if the url you want to get data from is correct.
check if console logged any errors.
Also quote from http://api.jquery.com/jquery.getjson/
"Additional Notes:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
Script and JSONP requests are not subject to the same origin policy restrictions."
I found out that following issue occurs on safari via Javascript, jQuery Ajax:
I make a cors simple request using GET
Server responses with 302
Safari follows redirect but uses OPTIONS instead of GET as method, so it does a preflight request
I would expect that step 3 would also invoke a simple request using GET, which is exactly how it is done in Chrome and Firefox.
The problem is that the server who responses to the request after step 3 can not handle requests with method OPTIONS and therefor fails with status "Method Not Allowed".
Since i have no influence on the server side, i need to force either to not follow the redirect automatically and do it manually instead or somehow tell safari not to switch to OPTIONS.
Is there any way to do one of those options?
Is there a difference between an AJAX request and a direct browser request (in terms of how a web page is called and loaded)?
In other words, I mean: is a direct server-side request handled in any way differently than a client-side request (initiated by the browser)?
There may be some header differences, but the main behavior difference is on the client.
When the browser makes a regular request as in window.location.href = "index.html", it clears the current window and loads the server response into the window.
With an ajax request, the current window/document is unaffected and javascript code can examine the results of the request and do what it wants to with those results (insert HTML dynamically into the page, parse JSON and use it the page logic, parse XML, etc...).
The server doesn't do anything different - it's just in how the client treats the response from the two requests.
An AJAX request is identical to a "normal" browser request as far as the server is concerned other than potentially slightly different HTTP headers. e.g. chrome sends:
X-Requested-With:XMLHttpRequest
I'm not sure if that header is standardized or not, or if it's different in every browser or even included at all in every browser.
edit: I take that back, that header is sent by jQuery (and likely other JS libraries), not the browser as is evidenced by:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/');
xhr.send();
which sends:
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie: ....
Host:stackoverflow.com
If-Modified-Since:Sat, 31 Dec 2011 01:57:24 GMT
Referer:http://stackoverflow.com/questions/8685750/how-does-an-ajax-request-differ-from-a-normal-browser-request/8685758
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11
which leads me to the conclusion that by default there is absolutely no difference.
Some popular client-side libraries like jQuery include the X-Requested-With header in their requests and set it to XMLHttpRequest to mark them as AJAX.
This seems to have been considered standard enough a few years ago (probably due to the huge popularity of jQuery and its presence in almost every website) that many server-side frameworks even have helpers that take care of checking for this header in the received request for you:
ASP.NET MVC 5:
HttpRequestBase.IsAjaxRequest()
Django:
HttpRequest.is_ajax()
Flask:
flask.Request.is_xhr
However, it seems that with the end of jQuery's reign in the front end world and the standardization of the fetch API and the rise of other modern client-side libraries that don't add any header for this purpose by default, the pattern has fallen into obsolescence also in the backend; with ASP.NET MVC not including the helper in newer versions and Flask marking it as deprecated.
Not really. Except that most Ajax clients send a X-Requested-With=XMLHttpRequest HTTP header
I always check if "text/html" is the request's "best" Accept mimetype, because browsers always send that as the first.
Firefox example:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Of course, this may still be a ajax request with text/html as the Accept mimetype, but I found this to be reliable when you know what client will consume your backend api.
An AJAX request in Blink and Gecko-powered browsers (Firefox, Chrome, Edge etc) will send this header with AJAX requests:
Sec-Fetch-Dest: empty
That means that:
The destination is the empty string. This is used for destinations that do not have their own value. For example fetch(), navigator.sendBeacon(), EventSource, XMLHttpRequest, WebSocket, etc.
Safari does not send this header at the time of writing (and IE never has and never will, but it's only a few months before IE should be completely irrelevant).
your user-agent, aka browser, sends an XHR header which you can catch from php like this:
$_SERVER['HTTP_X_REQUESTED_WITH']