繁体   English   中英

为什么在服务器端设置 Access-Control-Allow-Origin 后仍然出现跨源错误?

[英]Why there is still a cross oorigin error after setting the Access-Control-Allow-Origin in server side?

我刚刚运行了一个 CORS 跨域演示。演示与 node.js 一起运行。 这里是索引。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);
});

你可以看到我已经用http://localhost:3000设置了Access-Control-Allow-Origin ,所以对预检请求的响应实际上应该通过访问控制检查,这意味着请求无论如何都会成功。但是当我go 到端口 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
});

根据为什么不将 CORS 标头添加到 OPTIONS 路由允许浏览器访问我的 API? . 但是错误仍然存在。

您发布的代码应该可以工作。

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);
});

尝试点击这个 repl。

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

您还需要使用 header Access-Control-Allow-Methods http 动词:

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

这个答案有更详细的描述: Why does not adding CORS headers to an OPTIONS route allow browsers to access my API?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM