【发布时间】:2022-11-17 02:24:46
【问题描述】:
我有一个简单的提取:
fetch('http://mydomain.local:5000/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'access-control-allow-credentials' : true
},
body: JSON.stringify({
username : "admin",
password : "123"
})
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
连接到后端:
app.use(cors({credentials: true, origin: 'http://mydomain.local:5173/'}));
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
next();
});
但我得到:
Access to fetch at 'http://mydomain.local:5000/auth' from origin 'http://mydomain.local:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://mydomain.local:5173/' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我试图通过启用原点并上下移动 cors 来绕过它,但我找不到绕过它的方法。我该如何解决这个问题?
【问题讨论】: