No 'Access-Control-Origin' header is present on the requested resource
时间: 2024-08-12 07:04:02 浏览: 31
当浏览器尝试发起一个跨域请求时,如果服务器返回的响应头中没有包含`Access-Control-Allow-Origin`字段,就会收到类似 "No 'Access-Control-Allow-Origin' header is present on the requested resource" 的错误提示。这通常是因为服务器没有明确允许来自特定源的跨域请求。
`Access-Control-Allow-Origin` 是 CORS(Cross-Origin Resource Sharing,跨源资源共享)协议的一部分,它告诉浏览器哪些源(通常是域名)被允许接收响应数据。如果服务器设置了 `*` 或者客户端请求的源(即`Origin`请求头的值),则表示任意源都可以接收响应;如果没有设置或者只设置了特定源,那么只有那些列在允许列表中的源才能成功接收跨域数据。
为了修复这个问题,你需要在服务器端设置适当的响应头,例如如果你希望只允许特定的域访问资源,你可以这样做:
```javascript
// Node.js 使用 express 框架示例
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://example.com');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
next();
});
```
然后在发送跨域请求时,确保你的前端代码也包含了正确的 `Origin` 请求头,比如:
```javascript
axios.get('/api/data', {
headers: {
'Origin': 'http://example.com',
},
})
```