1

I am having trouble using the express/node. I created a route called "/searching" which is working fine because I already tested it. I also have an html file which is not part of the express project; It is not located in the 'public' or in the 'views' folders. I am trying the access the '/searching' route from this file. I saw in the cmd that the request is being done, but I can't retrieve the data from the ajax I am doing.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>    
<body>
<p id="container">Hello</p>    
<script>
      $(document).ready(function(){
        $("#container").click(function(){
            $.get('http://localhost:3000/searching',function(data){
                 $("#container").html(data);      
            });  });  });
</script>    
</body>     
</html>

The node/express part that corresponds to the route is:

app.get('/searching', function(req, res){
    res.send("result");
});

I expect to see the "Hello" text changed to "result" when I click this, but it is not working. Any suggestion?

jo_va
  • 13,504
  • 3
  • 23
  • 47
Joel
  • 336
  • 3
  • 14
  • Is page being served from port 3000 also? If not it's a cross domain request and you would see warning in browser console. Also you can inspect actual request in browser dev tools network for more clues and also should add an ajax error handler for same – charlietfl May 29 '16 at 00:11
  • No, the html is being opened from the folder "file:///C:/... – Joel May 29 '16 at 00:12
  • OK.. can't make ajax requests from `file://` protocol for security reasons. Open page on a server. Learn to use browser dev tools (F12) and all this could be figured out from there – charlietfl May 29 '16 at 00:13
  • I served the html file from another port. I see the request is being done via cmd. With F12 I see this error: XMLHttpRequest cannot load http://localhost:3000/searching. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. – Joel May 29 '16 at 00:20
  • So research that error by pasting in google. You either need to serve from same server as ajax is calling or implement CORS on data server – charlietfl May 29 '16 at 00:22
  • Attempted this approach http://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue, but still have the problem. – Joel May 29 '16 at 00:52
  • I don't do lot in node except local development of front end apps but there are cors modules for node you can install – charlietfl May 29 '16 at 01:13

0 Answers0