簡體   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