1

I just run a CORS cross origin demo.The demo is running with node.js. Here is the index.html:

<button>click to cross origin using CROS</button>
<p>hello world </p>
<script>
    var btn = document.getElementsByTagName('button')[0];
    var text = document.getElementsByTagName('p')[0];
    btn.addEventListener('click', function () {
        var xhr = new XMLHttpRequest();
        var url = 'http://localhost:3001';    
        xhr.open('PUT',url,true);                
        xhr.send();                       
        xhr.onreadystatechange = () => {     
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {  
                text.innerHTML = xhr.response;
            }
        }
    })
</script>

Here is the serverRes.js:

var express = require('express');
var app = express();
var responsePort = 3001;  
app.get('/', (req, res) => {
    res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); 
    res.send("Hello world from CROS.");  
});

app.listen(responsePort, function () {
    console.log('cros_responser is listening on port '+ responsePort);
});

You can see that I have set the Access-Control-Allow-Origin with http://localhost:3000,so the response to the preflighted request should actually pass the access control check,which means the request will succeed anyway.But when I go to the port 3000,what I get is:

enter image description here

But why?Why there is still a cross oorigin error after setting the Access-Control-Allow-Origin in server side? Also,I have tried writing:

app.all('/', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.send("Hello world from CROS.");   
    next(); // pass control to the next handler
});

according to Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?. But the error still exists.

Chor
  • 833
  • 1
  • 5
  • 14
  • Possible duplicate of [Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?](https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my) – The Fabio Nov 09 '19 at 06:51

2 Answers2

2

The code you posted should work.

var express = require('express');
var app = express();
var responsePort = 3001;  


app.all("/", function(req, res, next){
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next();
});


app.get('/', (req, res) => {
    res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); 
    res.send("Hello world from CROS.");  
});

app.listen(responsePort, function () {
    console.log('cros_responser is listening on port '+ responsePort);
});

Try hitting this repl instead.

https://repl.it/@nithinthampi/WirelessGentleSigns

Nithin Thampi
  • 3,579
  • 1
  • 13
  • 13
0

you also need to allow the http verbs with the header Access-Control-Allow-Methods:

res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');

This answer has a more detailed description: Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

The Fabio
  • 5,369
  • 1
  • 25
  • 55
  • No,it does not work. I changed the code to `app.all('/', function (req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.send("Hello world from CROS."); next(); });`,but nothing changes.Still an error. – Chor Nov 09 '19 at 07:18
  • maybe I missed the "OPTIONS" method... I will add it – The Fabio Nov 09 '19 at 07:36
  • did you follow the instruction on the link i posted? – The Fabio Nov 09 '19 at 07:37
  • your comment does not have the OPTIONS method... look at the updated answer – The Fabio Nov 09 '19 at 07:46
  • I will try it.But my request is PUT,why need to set Access-Control-Allow-Methods including OPTIONS? – Chor Nov 09 '19 at 07:47
  • it is part of CORS, if you look at the request of the error you posted, it happens on the OPTIONS call, which is the normal behavior – The Fabio Nov 09 '19 at 07:56