Javascript 跨域请求仅支持 HTTP,但不支持跨域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8449716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:03:38  来源:igfitidea点击:

Cross origin requests are only supported for HTTP but it's not cross-domain

javascript

提问by siannone

I'm using this code to make an AJAX request:

我正在使用此代码发出 AJAX 请求:

$("#userBarSignup").click(function(){
    $.get("C:/xampp/htdocs/webname/resources/templates/signup.php",
        {/*params*/},
        function(response){
            $("#signup").html("TEST");
            $("#signup").html(response);
        },
        "html");

But from the Google Chrome JavaScript console I keep receiving this error:

但是从 Google Chrome JavaScript 控制台我不断收到这个错误:

XMLHttpRequest cannot load file:///C:/xampp/htdocs/webname/resources/templates/signup.php. Cross origin requests are only supported for HTTP.

XMLHttpRequest 无法加载 file:///C:/xampp/htdocs/webname/resources/templates/signup.php。跨源请求仅支持 HTTP。

The problem is that the signup.phpfile is hosted on my local web server that's where all the website is run from so it's not cross-domain.

问题是signup.php文件托管在我的本地 Web 服务器上,所有网站都在该服务器上运行,因此它不是跨域的。

How can I solve this problem?

我怎么解决这个问题?

采纳答案by Petesh

You need to actually run a webserver, and make the get request to a URI on that server, rather than making the get request to a file; e.g. change the line:

您需要实际运行一个网络服务器,并向该服务器上的 URI 发出获取请求,而不是向文件发出获取请求;例如改变行:

    $.get("C:/xampp/htdocs/webname/resources/templates/signup.php",

to read something like:

阅读以下内容:

    $.get("http://localhost/resources/templates/signup.php",

and the initial request page needs to be made over http as well.

并且初始请求页面也需要通过 http 进行。

回答by prauchfuss

I've had luck starting chrome with the following switch:

我很幸运使用以下开关启动 chrome:

--allow-file-access-from-files

On os x try (re-type the dashes if you copy paste):

在 os x 上尝试(如果复制粘贴,请重新键入破折号):

open -a 'Google Chrome' --args -allow-file-access-from-files

On other *nix run (not tested)

在其他 *nix 运行(未测试)

 google-chrome  --allow-file-access-from-files

or on windows edit the properties of the chrome shortcut and add the switch, e.g.

或在 Windows 上编辑 chrome 快捷方式的属性并添加开关,例如

 C:\ ... \Application\chrome.exe --allow-file-access-from-files

to the end of the "target" path

到“目标”路径的末尾

回答by Pramod Alagambhat

If you're working on a little front-end project and want to test it locally, you'd typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they're placed in your local directory, you might see warnings like this:

如果您正在处理一个小的前端项目并希望在本地测试它,您通常会通过在 Web 浏览器中指向您的本地目录来打开它,例如输入 file:///home/erick/mysuperproject/index .html 在您的 URL 栏中。但是,如果您的站点正在尝试加载资源,即使它们位于您的本地目录中,您也可能会看到如下警告:

XMLHttpRequest cannot load file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP.

XMLHttpRequest 无法加载 file:///home/erick/mysuperproject/mylibrary.js。跨源请求仅支持 HTTP。

Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you'd need to mount a webserver to run your project there.

Chrome 和其他现代浏览器已经对跨域请求实施了安全限制,这意味着您无法通过 file:/// 加载任何内容,您需要始终使用 http:// 协议,即使是本地 - 由于同源策略。就这么简单,您需要安装一个网络服务器才能在那里运行您的项目。

This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you're running several other projects), node.js with express, a Ruby server, etc. or simply modifying your browser settings.

这不是世界末日,有很多解决方案,包括旧的 Apache(如果您正在运行其他几个项目,则使用 VirtualHosts)、带有 express 的 node.js、Ruby 服务器等,或者只是修改您的浏览器设置。

However there's a simpler and lightweight solution for the lazy ones. You can use Python's SimpleHTTPServer. It comes already bundled with python so you don't need to install or configure anything at all!

然而,对于懒惰的人来说,有一个更简单和轻量级的解决方案。您可以使用 Python 的 SimpleHTTPServer。它已经与 python 捆绑在一起,因此您根本不需要安装或配置任何东西!

So cd to your project directory, for instance

所以 cd 到你的项目目录,例如

1 cd /home/erick/mysuperproject and then simply use

1 cd /home/erick/mysuperproject 然后简单地使用

1 python -m SimpleHTTPServer And that's it, you'll see this message in your terminal

1 python -m SimpleHTTPServer 就是这样,您将在终端中看到此消息

1 Serving HTTP on 0.0.0.0 port 8000 ... So now you can go back to your browser and visit http://0.0.0.0:8000with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I'm in a rush to test a new library or work out a new idea.

1 在 0.0.0.0 端口 8000 上提供 HTTP 服务……所以现在您可以返回浏览器并访问http://0.0.0.0:8000那里提供的所有目录文件。您可以配置端口和其他内容,只需查看文档即可。但是当我急于测试一个新库或想出一个新想法时,这个简单的技巧对我有用。

There you go, happy coding!

你去,快乐编码!

EDIT:In Python 3+, SimpleHTTPServer has been replaced with http.server. So In Python 3.3, for example, the following command is equivalent:

编辑:在 Python 3+ 中,SimpleHTTPServer 已替换为 http.server。因此,例如,在 Python 3.3 中,以下命令是等效的:

python -m http.server 8000

回答by thehme

I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install nodefirst.

我在尝试加载使用 JSON 数据填充页面的简单 HTML 文件时遇到了同样的错误,所以我使用了 node.js 和 express 来解决这个问题。如果没有安装node,需要先安装node

  1. Install express npm install express

  2. Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server

  3. Put something like the following in the server.js file and read about this on the expressgihub site:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    // __dirname will use the current path from where you run this file 
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
    
    app.listen(8000);
    console.log('Listening on port 8000');
    
  4. After you've saved server.js, you can run the server using:

  1. 安装快递 npm install express

  2. 在项目的根文件夹中创建一个 server.js 文件,在我的例子中是我想要服务器的文件上方的一个文件夹

  3. 在 server.js 文件中放入类似以下内容,并在expressgihub 站点上阅读相关内容:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    // __dirname will use the current path from where you run this file 
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
    
    app.listen(8000);
    console.log('Listening on port 8000');
    
  4. 保存 server.js 后,您可以使用以下命令运行服务器:

node server.js

node server.js

  1. Go to http://localhost:8000/FILENAMEand you should see the HTML file you were trying to load
  1. 转到http://localhost:8000/FILENAME,您应该会看到您尝试加载的 HTML 文件

回答by Rahul Reddy

If you have nodejs installed, you can download and install the server using command line:

如果你安装了 nodejs,你可以使用命令行下载并安装服务器:

npm install -g http-server

Change directories to the directory where you want to serve files from:

将目录更改为要从中提供文件的目录:

$ cd ~/projects/angular/current_project 

Run the server:

运行服务器:

$ http-server 

which will produce the message Starting up http-server, serving on:

这将产生消息正在启动 http-server,服务于:

Available on: http://your_ip:8080and http://127.0.0.1:8080

可在: http://your_ip:8080http://127.0.0.1:8080

That allows you to use urls in your browser like

这允许您在浏览器中使用网址,例如

http://your_ip:8080/index.html

http://your_ip:8080/index.html

回答by ken4ward

It works best this way. Make sure that both files are on the server. When calling the html page, make use of the web address like: http:://localhost/myhtmlfile.html, and not, C::///users/myhtmlfile.html. Make usre as well that the url passed to the json is a web address as denoted below:

这种方式效果最好。确保这两个文件都在服务器上。调用 html 页面时,请使用以下网址:http:://localhost/myhtmlfile.html,而不是C::///users/myhtmlfile.html。让 usre 传递给 json 的 url 是一个网址,如下所示:

$(function(){
                $('#typeahead').typeahead({
                    source: function(query, process){
                        $.ajax({
                            url: 'http://localhost:2222/bootstrap/source.php',
                            type: 'POST',
                            data: 'query=' +query,
                            dataType: 'JSON',
                            async: true,
                            success: function(data){
                                process(data);
                            }
                        });
                    }
                });
            });

回答by Yogesh Jog

REM kill all existing instance of chrome 
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
  1. change chromeLocation path with yours.

  2. save above as .bat file.

  3. drag drop you file on the batch file you created. (chrome does give restore pages option though so if you have pages open just hit restore and it will work).

  1. 使用您的更改 chromeLocation 路径。

  2. 将上面保存为 .bat 文件。

  3. 将您的文件拖放到您创建的批处理文件上。(Chrome 确实提供了恢复页面选项,因此如果您打开了页面,只需点击恢复即可使用)。

回答by Pranav Kasetti

You can also start a server without python using php interpreter.

您还可以使用 php 解释器在没有 python 的情况下启动服务器。

E.g:

例如:

cd /your/path/to/website/root
php -S localhost:8000

This can be useful if you want an alternative to npm, as php utility comes preinstalled on some OS' (including Mac).

如果您想要替代 npm,这会很有用,因为某些操作系统(包括 Mac)上预装了 php 实用程序。