Reputation: 981
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:
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.
Upvotes: 1
Views: 45
Reputation: 3679
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
Upvotes: 2
Reputation: 6250
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?
Upvotes: 0