一、基础概念
http://example.com
下的页面不能直接访问https://another - example.com
下的资源(协议不同),或者http://example.com:8080
不能访问http://example.com
(端口不同)。二、相关优势
三、类型
Accept
、Accept - Language
、Content - Language
、Content - Type
等特定头信息)。对于简单请求,浏览器会在请求头中添加Origin
字段表明请求来源,服务器如果允许该源的访问,会直接返回响应。Access - Control - Allow - Origin
等相关头信息,然后浏览器才会发送实际的跨域请求。四、应用场景
五、遇到的问题及解决方法
No 'Access - Control - Allow - Origin' header is present on the requested resource
。Access - Control - Allow - Origin
头,其值可以是特定的源(如http://example.com
)或者*
(表示允许所有源,但不适用于带有凭证的请求)。对于预检请求,服务器除了设置Access - Control - Allow - Origin
外,还需要根据实际情况设置Access - Control - Allow - Methods
(允许的请求方法)、Access - Control - Allow - Headers
(允许的自定义请求头)等头信息。cors
中间件来方便地处理跨域问题。示例代码如下:const express = require('express');
const cors = require('cors');
const app = express();
// 使用cors中间件,默认允许所有源
app.use(cors());
// 如果要指定允许的源
// app.use(cors({
// origin: 'http://example.com'
// }));
app.get('/data', (req, res) => {
res.json({ message: 'This is data from the server' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Access - Control - Allow - Origin
不能设置为*
,并且服务器需要在响应头中设置Access - Control - Allow - Credentials
为true
。app.use(cors({
origin: 'http://example.com',
credentials: true
}));
同时,在Axios客户端请求时,需要设置withCredentials
为true
:
axios.get('http://server - domain.com/data', {
withCredentials: true
}).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
领取专属 10元无门槛券
手把手带您无忧上云