ajax跨域方法之CORS跨域总结

php端添加

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Headers: content-type');

header('Access-Control-Allow-Methods: POST');

 

nodejs 配置全站路由都允许跨域

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials','true');
    next();
};
app.use(allowCrossDomain);

标准的CORS请求不对cookies做任何事情,既不发送也不改变。如果希望改变这一情况,就需要将withCredentials设置为true。

xhr.withCredentials = true;

服务端在处理这一请求时,也需要将Access-Control-Allow-Credentials设置为true

 

//allow custom header and CORS
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

  if (req.method == 'OPTIONS') {
    res.send(200); /让options请求快速返回/
  }
  else {
    next();
  }
});

nodejs接口转发代理中间件配置cros示例

var http = require('http')
var proxy = require('express-http-proxy');
var app = require('express')();
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials','true');
    next();
};
app.use(allowCrossDomain);
app.use('/', proxy('http://fanyi.baidu.com/'));

  http.createServer(app).listen(580, function () {
    console.log('server listening on port ' + 580);
});

 

 

angular 需要添加请求头  http://blog.sina.com.cn/s/blog_5be1dc830101k2ds.html

 $http({

    url:'http://10.97.204.88:8000/authenticate',

    method:"POST",

    headers: {

         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

    },

    data:$scope.user

  })

 

 

 

 

 

 

 

 

你可能感兴趣的:(Js,Nodejs)