跨域访问是指在浏览器端,当前访问的网页所在的域名与请求的资源所在的域名不同,浏览器会禁止该资源的访问。
JavaScript进行跨域访问需要使用CORS(Cross-Origin Resource Sharing)跨域资源共享或者JSONP(JSON with Padding)跨域数据请求。
在服务端设置响应头Access-Control-Allow-Origin,允许指定来源的跨域访问。
// node.js express框架设置CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
JSONP是通过在页面中动态添加<script>标签,将需要获取的数据返回到指定的回调函数中。
function jsonp(url, callback) {
const script = document.createElement('script');
script.src = url + '?callback=' + callback;
document.body.appendChild(script);
}
jsonp('http://example.com/data', 'handleData');
function handleData(data) {
console.log(data);
}