XMLHttpRequest无法加载。请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许访问来源。

6

我正在使用Apache httpd服务器来托管客户端文件。

http://ipaddress:8010/

我的Nodejs服务器运行在http://ipaddress:8087

当我发送POST请求时,会显示以下错误:

XMLHttpRequest cannot load http://ipaddress:8010/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ipaddress:8087' is therefore not allowed access.

我的客户端代码是:

    $.ajax({
  type: "POST",

  url: "http://ipaddress:8010",
  data: {name:"xyz"},
  success: function(){
  alert("success");
  },
  dataType: "json"
});

我的服务器端是:

response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');


    response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');


    response.setHeader('Access-Control-Allow-Credentials', true);

虽然允许了选项,但它仍然无法工作。有人能建议一下具体问题是什么吗?我在服务器端收到请求,但无法发送任何响应。

提前感谢:)


1
http://en.wikipedia.org/wiki/Same-origin_policy - Adil Shaikh
2个回答

9
错误信息如下:

没有“Access-Control-Allow-Origin”头

您设置了三个Access-Control-Allow-SOMETHING头,但没有一个是Origin


2
那么,解决方案是什么? - Cute Bear
发送适当的 Access-Control-Allow-Origin 标头。 - Quentin

6

您需要启用CORS。

要在Apache中添加CORS头,请在服务器配置文件或.htaccess文件的<Directory><Location><Files><VirtualHost>部分内添加以下行:

Header set Access-Control-Allow-Origin "*"

请参考此链接了解关于Apache的内容:

http://enable-cors.org/server_apache.html

对于Express,您可以添加中间件来设置响应所需的标头。

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();      
}); 

http://enable-cors.org/server_expressjs.html


1
该代码显示OP已经知道他们需要启用CORS(只是做错了)。该代码还显示他们没有使用Apache,虽然他们可能正在使用Express。无论哪种方式,在Stackoverflow上都应避免仅限链接的答案。 - Quentin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接