Access to XMLHttpRequest at 'file:///D:/xx/xxx.json' from origin 'null' has been blocked by CORS problem solving

Problem :
The wrong page in the console output in Chrome is as follows:
insert image description here

Error message:

Access to XMLHttpRequest at 'file:///D:/xxxx/xxx.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

The xxx.json here is a local JSON file.

Occurrence scenario :
Instead of starting the server or sencha app watchstarting the development server, test Ext JS related functions with a single file, that is, use Chrome to directly open a local html file. In the source code of this file, proxy is used to obtain data, and the data source uses a file named mydata.json.

			proxy : {
				type : 'ajax',
				url : 'mydata.json',
			}

Reason and analysis :
Open the local html file in the browser, the url in the proxy above obtains a local file, the protocol is file://, if it is started on the server, the http or https protocol is used.
For security reasons, Chrome prohibits this usage by default. The file protocol is different from the http/https protocol and will be considered by Chrome as cross-domain access, so it will be reported by CORS (Cross-Origin Resource Sharing, cross-domain resource sharing). Security policy blocks.
For the basic introduction of cross-domain, you can refer to Related concepts and solutions of cross-domain
access Although Chrome does not allow this use by default, you can allow access by modifying the browser's configuration or setting startup parameters. The set parameter is --allow- file-access-from-files.

Workaround :

There are two common ways to set this parameter:

  1. Method 1, start Chrome at the command line.
    Assuming that the installation path of Chrome is C:\Program Files (x86)\Google\Chrome\Application\chrome.exe, the command line startup command is as follows:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

The effect is as follows:
insert image description here

  1. Method 2, set a shortcut

[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-AkqM8szK-1649716469090) (images/screenshot_1587134729399.png)]

**Note: ** You need to close all the running Chrome windows to take effect, otherwise even the modification will not take effect.

Guess you like

Origin blog.csdn.net/oscar999/article/details/124114343