XMLHttpRequest cannot load. The requested resource does not have an Access-Control-Allow-Origin header. Origin therefore not allowed

I am using apache httpd server to host client files

http://ipaddress:8010/ 

and my Nodejs server is running on http://ipaddress:8087

when i send a mail request then it shows the following error

 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. 

my client side code:

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

my server side:

 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); 

options are allowed, but it does not work, can someone tell me what the problem is? I am receiving a server side request but cannot send any response.

early:)

+6
source share
2 answers

The error message says:

No header Access-Control-Allow-Origin

You have set three Access-Control-Allow-SOMETHING headers, but none of them are Origin .

+9
source

You will need to enable CORS.

To add CORS headers to apache, add the following line inside the <Directory> , <Location> , <Files> or <VirtualHost> section of the server configuration file or in the .htaccess file:

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

refer to this link for apache

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

For express, you can add middleware that will set the required headers for the response

 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

+6
source

Source: https://habr.com/ru/post/974209/


All Articles