首页 > 解决方案 > Unable to get data from different origin/host JQuery Nodejs-Express

问题描述

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

标签: javascriptjquerynode.jsexpresscors

解决方案


推荐阅读