IT박스

XMLHttpRequest가 파일을로드 할 수 없습니다.

itboxs 2020. 7. 30. 10:13
반응형

XMLHttpRequest가 파일을로드 할 수 없습니다. 교차 출처 요청은 HTTP에 대해서만 지원됩니다.


다음과 같은 오류가 발생합니다.

XMLHttpRequest cannot load file:///C:/Users/richa.agiwal/Desktop/get/rm_Library/templates/template_viewSettings.html. Cross origin requests are only supported for HTTP. 

이 질문에 대한 답변이 이전에 있었지만 여전히 내 문제에 대한 해결책을 찾지 못했습니다. chrome.exe --allow-file-access-from-files명령 프롬프트에서 실행 시도 하고 파일을 로컬 파일 시스템으로 옮겼지만 여전히 같은 오류가 발생합니다.

나는 어떤 제안을 주셔서 감사합니다!


개인용 컴퓨터의 코드 편집기에서 HTML 및 Javascript를 작성하고 브라우저에서 출력을 테스트하는 등의 작업을 수행하는 경우에 대한 오류 메시지가 표시 될 수 Cross Origin Requests있습니다. 브라우저는 서버를 설정할 필요없이 브라우저에서 HTML을 렌더링하고 자바 스크립트, jQuery, angularJ를 실행합니다. 그러나 많은 웹 브라우저가 교차 사이트 공격을 감시하도록 프로그램되어 있으며 요청을 차단합니다. 웹 브라우저에서 하드 드라이브를 읽을 수있는 사람은 없습니다. Javascript를 실행하는 Notepad ++ 및 jQuery 및 angularJs와 같은 프레임 워크를 사용하여 완벽하게 작동하는 웹 페이지를 작성할 수 있습니다. Notepad ++ 메뉴 항목을 사용하여 모든 것을 테스트하십시오.RUN, LAUNCH IN FIREFOX. 웹 페이지를 만드는 좋은 방법이지만, 레이아웃, CSS 및 간단한 페이지 탐색 이외의 것을 만들기 시작하려면 컴퓨터에 로컬 서버가 설정되어 있어야합니다.

내가 사용하는 몇 가지 옵션이 있습니다.

  1. Firefox에서 웹 페이지를 로컬로 테스트 한 다음 호스트에 배포하십시오.
  2. 또는 : 로컬 서버를 실행하십시오.

Firefox에서 테스트하고 호스트에 배포

  1. Firefox는 현재 하드 드라이브에서 제공된 파일의 Cross Origin Request를 허용합니다
  2. 웹 호스팅 사이트는 매니페스트 파일로 구성된 폴더의 파일에 대한 요청을 허용합니다.

로컬 서버 실행

  • 컴퓨터에서 Apache 또는 Python과 같은 서버를 실행하십시오.
  • 파이썬은 서버가 아니지만 간단한 서버를 실행합니다.

파이썬으로 로컬 서버 실행

당신의 IP 주소를 얻으십시오 :

  • Windows : '명령 프롬프트'를여십시오. 모든 프로그램, 보조 프로그램, 명령 프롬프트
  • 나는 항상 Command Promptas를 실행합니다 Administrator. Command Prompt메뉴 항목을 마우스 오른쪽 버튼으로 클릭하고Run As Administrator
  • 명령을 ipconfig입력하고 Enter를 누르십시오.
  • IPv4 주소를 찾으십시오. . . . . . . . 12.123.123.00
  • 귀하의 IP 주소도 표시하는 웹 사이트가 있습니다

Python이 없으면 다운로드하여 설치하십시오.

'명령 프롬프트'를 사용하면 웹 페이지로 사용할 파일이있는 폴더로 이동해야합니다.

  • C : \ Root 디렉토리로 돌아가려면 cd /를 입력하십시오.
  • cd Drive : \ Folder \ Folder \ etc를 입력하여 .Html 파일이있는 폴더 (또는 PHP 등)로 이동하십시오.
  • 경로를 확인하십시오. 명령 프롬프트에서 경로를 입력하십시오. 파이썬이 위치한 폴더의 경로를 확인해야합니다. 예를 들어 python이 C : \ Python27에 있으면 나열된 경로에 해당 주소가 표시되어야합니다.
  • Python 디렉토리의 경로가 경로에 없으면 경로를 설정해야합니다. type : help path를 누르고 Enter를 누르십시오. 경로에 대한 도움말이 표시됩니다.
  • 다음과 같이 입력하십시오 : path c : \ python27 % path %
  • % path %는 모든 현재 경로를 유지합니다. 현재 경로를 모두 지우지 않고 새 경로를 추가하십시오.
  • 파일을 제공 할 폴더에서 새 경로를 작성하십시오.
  • Python 서버를 시작하십시오. 유형 : python -m SimpleHTTPServer port여기서 'port'는 원하는 포트 번호입니다 (예 :python -m SimpleHTTPServer 1337
  • 포트를 비워두면 기본값은 포트 8000입니다.
  • Python 서버가 성공적으로 시작되면 msg가 표시됩니다.

로컬로 웹 응용 프로그램 실행

  • 브라우저를 엽니 다
  • 주소 입력란에 다음을 입력하십시오. http://your IP address:port
  • http://xxx.xxx.x.x:1337또는 http://xx.xxx.xxx.xx:8000기본값
  • 서버가 작동하면 브라우저에 파일 목록이 표시됩니다
  • 제공하려는 파일을 클릭하면 표시됩니다.

고급 솔루션

  • 코드 편집기, 웹 서버 및 기타 통합 된 서비스를 설치하십시오.

아파치, PHP, Python, SQL, 디버거 등을 모두 컴퓨터에 별도로 설치 한 다음 모두 함께 작동하게 만드는 방법을 파악하거나 이러한 모든 것을 결합하는 솔루션을 찾는 데 많은 시간을 할애 할 수 있습니다.

NetBeans IDE와 함께 XAMPP를 사용하는 것이 좋습니다. User InterfaceApache 및 기타 서비스를 관리하고 통합 할 수있는 WAMP를 설치할 수도 있습니다.


간단한 솔루션

순수한 html / js / css 파일로 작업하는 경우

이 작은 서버 ( 링크 ) 앱을 크롬으로 설치하십시오 . 앱을 열고 파일 위치를 프로젝트 디렉토리로 지정하십시오.

앱에 표시된 URL로 이동하십시오.

편집 : Gulp를 사용하여 더 똑똑한 솔루션

1 단계 : Gulp 설치 터미널에서 다음 명령을 실행하십시오.

npm install gulp-cli -g
npm install gulp -D

Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.

var gulp        = require('gulp');
var bs          = require('browser-sync').create();   

gulp.task('serve', [], () => {
        bs.init({
            server: {
               baseDir: "./",
            },
            port: 5000,
            reloadOnRestart: true,
            browser: "google chrome"
        });
        gulp.watch('./**/*', ['', bs.reload]);
});

Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command

npm install browser-sync gulp --save-dev

Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command

gulp serve

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs


I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:

localhost//myAPIProject

Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.

http://localhost//myAPIProject


If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).


Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!


To add to Alan Wells's elaborate answer here is a quick fix

Run a Local Server

you can serve any folder in your computer with Serve

First, navigate using the command line into the folder you'd like to serve.

Then

npx i -g serve
serve

or if you'd like to test Serve with downloading it

npx serve

and that's it! You can view your files at http://localhost:5000

enter image description here


Place your project folder into the htdocs of the Xampp directory Start your Apache server using xampp control panel then open a browser goto localhost/projectfolder then it start working

참고URL : https://stackoverflow.com/questions/20041656/xmlhttprequest-cannot-load-file-cross-origin-requests-are-only-supported-for-ht

반응형