0

In Node.js (or in any web server for that matter), is it somehow possible to be able to determine whether a resource request came from an embedded element in an html document, as opposed to a scripted request?

For instance, if I have this in my .html file:

<script src="/testRoute.js"></script>

And this in my javascript:

var xhr = new XMLHttpRequest();
xhr.open("GET", '/testRoute.js', true);
xhr.send();

is there a way the server can distinguish between these two requests?

The Same Origin Policy applies differently in each case, so there is apparently some differentiation going on (at least under the surface). Is there a way the server developer can see the difference?


Just as a personal experiment, using a diff tool, I compared an express req object received with each and saw only two slight differences:

  1. The socket, connection, and client properties in the <script> originating req object had [function]s for their error property, whereas these were [object] for the request that originated as an XMLHttpRequest.

  2. The headers property contained cache-control: 'max-age=0' in the request that originated as an XMLHttpRequest but not for the <script> request.

I don't really know what that means, and I don't know if these results are consistent across browsers, but they were consistent at least between Chrome and Firefox.

NanoWizard
  • 2,104
  • 1
  • 21
  • 34
  • 1
    Yes, the headers might be different. Some frameworks e.g. set the `X-REQUESTED-WITH`-Header on XMLHttpRequests. But in general, no, there is no designated header to tell the difference, both are plain HTTP requests. – Bergi Nov 03 '14 at 01:32
  • @Bergi thanks! Your comment led to me finding [this SO question](http://stackoverflow.com/questions/17478731/whats-the-point-of-x-requested-with-header) which explains the `X-REQUESTED-WITH` header quite nicely. So does this mean I could add that header myself for each request I want to be distinguishable? – NanoWizard Nov 03 '14 at 01:42
  • Yes, if you want the requests to be distinguishable you should set such a header for every ajax call. – Bergi Nov 03 '14 at 01:55

0 Answers0