javascript跨域访问

JSONP
$.getJSON("http://localhost:9011/getData?callback=?", function(data){
    console.log(data);// "hello world"
});

server
app.get("/getData", function(req, res, next){
    var data = "hello world";
    res.send(req.query.callback+"("+data+")");
});

需要前后端配合,约定回调的函数名字。callback为req.query的属性,函数的结果以String的形式发送到前端
注: JSONP只支持GET提交,且需要前后端共同约定回调函数的名字





CORS(Cross-origin resource sharing)
req.header("Access-Control-Allow-Origin","*");//表示接受任意域名的请求
req.header("Access-Control-Allow-Methods","GET,POST");//它的值是逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法
原文地址:https://www.cnblogs.com/sxshijingjing/p/6480537.html