推荐阅读:https://segmentfault.com/a/1190000012469713

正常的ajax请求
S:跨域 - 图1

CORS 配置解决跨域

Node.js后台配置(express框架)

  1. app.all('*', function(req, res, next) {
  2. res.header("Access-Control-Allow-Origin", "*"); // 主要是配置这个!!!
  3. res.header("Access-Control-Allow-Headers", "X-Requested-With");
  4. res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  5. res.header("X-Powered-By", ' 3.2.1')
  6. //这段仅仅为了方便返回json而已
  7. res.header("Content-Type", "application/json;charset=utf-8");
  8. if(req.method == 'OPTIONS') {
  9. //让options请求快速返回
  10. res.sendStatus(200);
  11. } else {
  12. next();
  13. }
  14. });