-2

I have this JQuery code but its not getting success always giving following:

XMLHttpRequest cannot load http://localhost:8080/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (17:21:10:896 | error, javascript)
  at win_1.html
Error: undefined (17:21:10:902)
  at win_1.html:18
Debugging session with browser was closed.

index.html:

<script src=http://code.jquery.com/jquery-1.11.2.min.js ></script>
<body>
response here: <p id="lblResponse">fill me in</p>
<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
    url: 'http://localhost:8080',
    // dataType: "jsonp",
    data: '{"data": "TEST"}',
    type: 'POST',
    //jsonpCallback: 'callback', // this is not relevant to the POST anymore
    success: function (data) {
      var ret = jQuery.parseJSON(data);
      $('#lblResponse').html(ret.msg);
      console.log('Success: ')
    },
    error: function (xhr, status, error) {
      console.log('Error: ' + error.message);
      $('#lblResponse').html('Error connecting to the server.');
    },
    });
});
</script>
</body>

nodejs-server.js:

var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
  console.log('Request received: ');
  util.log(util.inspect(req)) 
  // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
  util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) 
  // this line logs just the method and url

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  req.on('data', function (chunk) {
      console.log('GOT DATA!');
  });
  res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8080);
console.log('Server running on port 8080');
  • possible duplicate of [No 'Access-Control-Allow-Origin' - Node / Apache Port Issue](http://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue) – Dave Apr 02 '15 at 15:26
  • NO - that does not solved the problem –  Apr 02 '15 at 15:28
  • where are you running this code? on localhost? – Ashkan Mobayen Khiabani Apr 02 '15 at 15:33
  • Both has to be run in localhost yes. –  Apr 02 '15 at 15:34
  • 2
    Same origin requires, same protocol, same host and **same port number**. **Your port numbers are different; 8080 vs 8383.** Bear mind that if you explicitly specify the default port number, you may also need to explicitly specify it in the ajax URL. – PeterKA Apr 02 '15 at 15:43
  • 2
    Look at the question dave linked to again - you're running services on two different ports, which makes them different domains. – Aaron Dufour Apr 02 '15 at 15:44
  • Programming is done to listen on port 8080 (showing in debug 8383 is false and BUG of the browser in my whole code i have no-where mentioned to use 8383) –  Apr 02 '15 at 15:49
  • 2
    The browser is saying that the javascript it is running was downloaded from `localhost:8383`. It is _very_ unlikely that this is a browser bug. Especially since your node server code has no way of serving static assets like the index.html you referenced. What URL do you go to in order to see this page? – Aaron Dufour Apr 02 '15 at 16:07
  • I have executed the page from NetBeans IDE, it runs its own webserver to execute the what-ever.html file so it used port 8383 to launch the html file. But it makes no sense why i have no connection with 8080? and its failing –  Apr 02 '15 at 16:09
  • Why in chrome there is no command line argument to ignore that stupid / nonsense XMLHttpRequest cannot load error? I am super admin i know i am why is it problem for Chrome to keep saying this error? XMLHttpRequest cannot load –  Apr 02 '15 at 16:12
  • 2
    There is a flag detailed [here](http://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome). I would strongly suggest you just add the header as suggested in the possible duplicate link, though. Turning off security features in chrome is very dangerous. With that flag set, any site you visit can access all of your data from any service you're logged in to. – Aaron Dufour Apr 02 '15 at 16:31
  • Executed with chromium-browser.exe --disable-web-security but still same error is happening –  Apr 02 '15 at 16:39
  • ping experts; hello??? –  Apr 03 '15 at 06:54

1 Answers1

0

Add this after your console.log():

console.log('Request received: '); if (req.method === 'OPTIONS') { //add needed headers var headers = {}; headers["Access-Control-Allow-Origin"] = "*"; headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS"; headers["Access-Control-Allow-Credentials"] = true; headers["Access-Control-Max-Age"] = '86400'; // 24 hours headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept"; // respond to the request res.writeHead(200, headers); res.end(); } else { //rest of your code }

Source: https://annasob.wordpress.com/2012/01/11/getting-around-cors-with-node-js/

  • 1
    Excellent. This is how questions should be answered. instead of minus voting. Appreciate it, exact to the point. –  Apr 16 '15 at 09:04