无法加载XMLHttpRequest.没有& # 39;Access-Control-Allow-Origin& # 3

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access

本文关键字:Access-Control-Allow-Origin XMLHttpRequest 没有 加载      更新时间:2023-09-26

我使用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);

选项允许,但它不工作,谁能建议到底是什么问题?我正在接收服务器端的请求,但无法发送任何响应。

提前感谢:)

错误提示:

没有'Access-Control-Allow-Origin'头

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

您需要启用CORS。

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

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