【发布时间】:2019-11-09 06:22:42
【问题描述】:
我刚刚运行了一个 CORS 跨源演示。该演示使用 node.js 运行。这是 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>
这里是 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);
});
你可以看到我已经设置了Access-Control-Allow-Origin和http://localhost:3000,所以对预检请求的响应实际上应该通过访问控制检查,这意味着请求无论如何都会成功。但是当我转到3000端口时,我得到的是:
但是为什么呢?为什么在服务器端设置了Access-Control-Allow-Origin后还是会出现cross origin错误? 另外,我试过写:
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
});
根据Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?。但是错误依然存在。
【问题讨论】:
标签: javascript node.js cross-domain