Posting from local html/javascript website to an o

2020-03-26 01:32发布

问题:

What I'm trying to do

Post from a local html/javascript website to an online PHP file.

Problem

When I attempt to utilise my below code, I keep receiving the below mentioned error.

Background:

This website is intended to run locally. As it's each user's choice which browser they use, I'm looking to discover an approach which could solve the above, without forcing browser policy modification onto each user.

Is this possible, if so how?

Javascript code:

$.ajax({
    type: 'POST',
    url: 'http://example.com/test.php',
    crossDomain: true,
    data: "my_request_is=foo",
    dataType: 'json',
    success: function(responseData, textStatus, jqXHR) 
    {
        console.log(responseData);
    },
    error: function (responseData, textStatus, errorThrown) 
    {
        console.warn(responseData, textStatus, errorThrown);
        alert('CORS failed - ' + textStatus);
    }
});

Php code (test.php):

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
echo json_encode(array("your_request_was" => $_POST['my_request_is']));
?>

Error:

回答1:

By default cross-origin requests are not allowed at chrome, chromium from file: protocol. You can close open instances of chrome, chromium and launch with --disable-web-security flag

google-chrome --disabled-web-security

or launch with existing instances open by setting a different user-data-dir

google-chrome --disable-web-security --user-data-dir="~/.config/google-chrome-temp"

is there an approach which could accomplish what I need to do, whilst not requiring me to modify the policies of local web-browsers?

Not at chrome, chromium without modifying default settings; or creating an chromium extension or app to perform network requests - where too, proper permissions need to be set.

The restriction is there for a purpose. One of the several security issues is that user at a local computer could, possibly unknowingly, upload a listing of all of the files in one or more directories on their computer, and potentially the directories themselves, without necessarily being aware of that fact, see

How FileReader.readAsText in HTML5 File API works?

which; note, could also occur without flags being set. Or, a requested script could perform actions to read or write to local filesystem without user necessarily being aware of their local filesystem being accessed by an external script.

Though, with restrictions in place, the user has to perform an affirmative action to disable default settings restricting access to local file system from file: protocol, and restricting local file system to fetch resources from null origin to a different origin.

As noted by @StefanoBalzarotti

sorry if I am fussy, but this limitation is not related to the 'file:' protocol, even with 'data:', 'about:' etc... you can't make a cross origin request. The requirement to make a cross origin request is to have an host for origin

which should be taken into consideration as to the reasons why browser developers would implement such a default limitation on cross origin request.

Used sparingly, and with awareness of the significance of the flags, the flags --disable-web-security and --allow-file-access-from-files, see

  • How do I make the Google Chrome flag “--allow-file-access-from-files” permanent?

  • List of Chromium Command Line Switches

are designed for local web development, not as a workaround for a local application which requires resources from a web application.

--disable-web-security Don't enforce the same-origin policy. (Used by people testing their sites.)

--allow-file-access-from-files By default, file:// URIs cannot read other file:// URIs. This is an override for developers who need the old behavior for testing.

"testing" term in description of flags should provide emphasis of the usage of the flags. The flags are not designed for production usage.


Alternatives,

  • Create a chromium extension to perform network tasks;

  • Create a chrome app to perform network tasks

where either requires proper permissions settings at manifest.json.



回答2:

Due to chrome security settings, to make an XMLHttpRequest you need a valid origin and a valid destination.
The destination is a valid domain, and because you have Access-Control-Allow-Origin enabled, you can make a request from different origin.
But the origin is not a valid domain, because you are doing a request from a local page.
The origin must be a valid host/identifier (domain for a website, identifier for a browser extension, application id for a webview embedded into an application).

You have these option to solve the issue:

  • Store your page on an host, that's fine localhost too, you can create a setup to automatically deploy the host and webpage to your customers
  • disable browser security settings: sample for chrome:

    chromium-browser --disable-web-security --user-data-dir

    check this answer, for how to use: https://stackoverflow.com/a/3177718/5081328

  • embed your page into an application and use a webview

  • Create a browser extension to load your page