0

I am trying to fetch simple data from a different host using JQuery Ajax request. Here is the example to reproduce:

Node.js express server file server.js:

var express = require('express');
var app = express();
var path = require('path');
// var cors = require('cors')
// app.use(cors());
app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
})

app.get('/', function(req, res) {
    console.log(res.getHeaders());
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(3000, function name(params) {
    console.log(`App listening on port 3000`);
});

This is the html file index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        console.log(`Request start`);
        $.ajax({
          type: "GET",
          url: "https://csrhub.com/number/",
          crossDomain: true,
          success: function(data, status) {
            console.log(data);
            alert("Thanks!");
          },
          error: function(jqXhr, textStatus, errorMessage) {
            console.log(textStatus);
            console.log(errorMessage);
          }
        });
      });
    </script>
  </head>
  <body>
    <p>This is a paragraph.</p>
  </body>
</html>

And upon file-load in Chrome I get this errors:

Console: enter image description here And here are the headers from the resource fetch: enter image description here enter image description here

The message is descriptive, but is this cros-origin-request really so uncommon? I mean it should be allowed frontend to request APIs for example.Can I make this work without chrome extensions workaround? I need this functionality in production. How to make this work?

EDIT Guys, did you read the answer my question is suggested to be duplicate of? This is not a duplicate. I am an owner of the server. I put the necessary headers. I also installed https://www.npmjs.com/package/cors and tried again. Same situation! I read the original question. The question and the context are not the same. This is not a duplicate. Why is this closed? I applied the necessary headers that allow CORS. It still doesnt work. Why?

Changed the code according to suggestions by @Joodjindy

Here is some more real time example https://youtu.be/ROWfnwBtQYE

Hairi
  • 2,253
  • 18
  • 40
  • "but is this cros-origin-request really so uncommon?" — Yes – Quentin Mar 12 '20 at 09:06
  • "I mean it should be allowed frontend to request APIs for example" — Convince csrhub.com of that then. – Quentin Mar 12 '20 at 09:07
  • first install cors with "npm install --save cors" then enable cors by writing "app.use(cors());" – Jood jindy Mar 12 '20 at 09:31
  • Same, not difference - still get this error. – Hairi Mar 12 '20 at 09:33
  • I dont understand how is this has been marked as duplicate. I own the server and frontend. The case is not the same – Hairi Mar 12 '20 at 09:42
  • you told the browser to ajax a request and you set the host to "https://csrhub.com" browser will consider this as cross-origin that's why – Jood jindy Mar 12 '20 at 09:45
  • try this **app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); ** – Jood jindy Mar 12 '20 at 09:45
  • @Joodjindy Removed `host` from the ajax, and applied the server code as you suggested. Same result :(. I edited my original post – Hairi Mar 12 '20 at 10:00
  • 2
    You don’t own the `https://csrhub.com/number/` server. That’s the server which needs to be CORS-enabled, not your own backend server. – sideshowbarker Mar 12 '20 at 10:40
  • i usually put 3 headers in php to enable CORS so try this "res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "*"); res.header("Access-Control-Allow-Methods", "*"); – Jood jindy Mar 12 '20 at 10:40
  • @sideshowbarker Wow - this is really a breakthrough. But we still can fetch this data via browser request. How csrhub server knows the GET request is not an usual browser get, but Ajax request? – Hairi Mar 12 '20 at 11:15
  • 1
    The csrhub server \*doesn’t\* know the GET request is not an usual browser get, but Ajax request. It doesn’t need to. It doesn’t care. With CORS, servers respond to requests regardless of how the requests are made. With CORS, servers don’t block requests. Instead CORS-enabled servers just send additional headers in responses. Browsers are where the restrictions are enforced. And even browsers don’t block requests; instead browsers block frontend code from accessing the \*responses\* to the requests. CORS is what tells browsers to lift the restrictions and un-block access to responses. – sideshowbarker Mar 12 '20 at 11:22
  • Everything in the comments is already covered by the duplicate question. . https://stackoverflow.com/a/35553666/19068 – Quentin Mar 12 '20 at 12:26
  • @sideshowbarker Ohhhh, I see now. Yes I understood it differently :( . I tried with setting the header `response.set_header('Access-Control-Allow-Origin', '*')` and it worked - chrome didnt complain anymore. One more off-topic question if I may :) - Why would csrhub not want to provide such functionality (to enable browsers ajax call )? Too much requests/traffic danger? – Hairi Mar 12 '20 at 12:51
  • I found why: https://stackoverflow.com/questions/15381105/cors-what-is-the-motivation-behind-introducing-preflight-requests?answertab=votes#tab-top – Hairi Mar 13 '20 at 07:12

0 Answers0