XMLHttpRequest无法加载.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许原点访问

Rah*_*hul 6 javascript jquery post json node.js

我使用apache httpd服务器来托管客户端文件

http://ipaddress:8010/
Run Code Online (Sandbox Code Playgroud)

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

当我发送邮件请求时,它显示以下错误

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.
Run Code Online (Sandbox Code Playgroud)

我的客户端代码是:

    $.ajax({
  type: "POST",

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

我的服务器端是:

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);
Run Code Online (Sandbox Code Playgroud)

允许的选项仍然没有用,任何人都可以提出究竟是什么问题?我在服务器端收到请求但无法发送任何响应.

提前致谢 :)

Que*_*tin 9

错误消息说:

没有'Access-Control-Allow-Origin'标题

您已设置三个Access-Control-Allow-SOMETHING标题,但它们都不是Origin.

  • 那么解决方案是什么? (2认同)

Yal*_*ber 6

您需要启用CORS.

在apache的添加CORS标头添加以下行内无论是<Directory>,<Location>,<Files><VirtualHost>服务器的配置文件或.htaccess文件内的部分:

Header set Access-Control-Allow-Origin "*"
Run Code Online (Sandbox Code Playgroud)

请参阅此链接了解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();      
}); 
Run Code Online (Sandbox Code Playgroud)

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