跨域(Cross-Origin Resource Sharing, CORS)是指在浏览器中运行的脚本尝试访问不同源(域名、协议或端口不同)的资源。由于同源策略(Same-Origin Policy)的限制,浏览器默认不允许这种行为,以防止安全问题。
问题:跨域请求被阻止,控制台显示“No 'Access-Control-Allow-Origin' header is present on the requested resource”。
原因:服务器没有正确设置CORS头部,或者设置的源与请求的源不匹配。
Node.js (Express) 示例:
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // 允许所有域,或指定特定域如 'http://example.com'
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.get('/data', (req, res) => {
res.json({ message: 'This is data from the server.' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Python (Flask) 示例:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/data')
def get_data():
response = jsonify({'message': 'This is data from the server.'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
if __name__ == '__main__':
app.run(port=3000)
确保前端代码正确发起请求,例如使用fetch
API:
fetch('http://yourserver.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
跨域问题通常是由于服务器未正确配置CORS头部导致的。通过在服务器端设置适当的CORS头部,可以有效解决这一问题,同时确保应用的安全性和灵活性。
领取专属 10元无门槛券
手把手带您无忧上云