跨域ajax调用失败-Angular.js节点js + express

Posted

技术标签:

【中文标题】跨域ajax调用失败-Angular.js节点js + express【英文标题】:Cross domain ajax call failed - Angular.js node js + express 【发布时间】:2013-11-26 09:54:49 【问题描述】:

我正在尝试从 angular.js 模块到 nodejs + express 服务器进行跨域调用,但我收到了未经授权的错误,或标头错误: 我遵循了 Cors 配置,但仍然遇到问题。

Angular.js 代码:

methods.getWelcomeApps = function (onSuccess, onError) 
        function makeBasicAuth(user, password) 
            var tok = user + ':' + password;
            var hash = btoa(tok);  // Base64 encoding
            return "Basic " + hash;
        

        var auth = makeBasicAuth(config.API.AppsList.username, config.API.AppsList.password);
        $http.defaults.useXDomain = true;
        $http(method: 'GET', url: config.API.AppsList.url,  headers: 'Authorization': auth)
            .success(onSuccess)
            .error(onError);
        ;

    return methods;
);

And the node.js code:

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', 'X-Requested-With');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') 
  return res.send(200);

return next();
;

我错过了什么吗?

谢谢。

【问题讨论】:

而具体的错误是...? 您不需要也允许 OPTIONS 吗? 【参考方案1】:

我认为这是不必要的

res.header('Access-Control-Allow-Headers', 'Content-Type');

这就够了

var allowCrossDomain = function(req, res, next) 
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
;

也许你有兴趣:

我的完整工作代码 - angularjs 客户端服务和nodejs 服务端:

客户端(angularjs v1.0.8)

motoads/app/js/services.js

var motoAdsServices = angular.module('motoAdsServices', ['ngResource']);

motoAdsServices.factory('Brand', ['$resource', function($resource) 
    return $resource('http://localhost\\:3000/api/:id', , 
      query: 
        method: 'GET',
        params: 
          id: 'brands'
        ,
        isArray: true
      
    );
  ]);

服务器(nodejs + express)

motoads/server/server.js

var express = require('express');
var path = require('path');
var http = require('http');
var brands = require('./routes/brands');

var app = express();

var allowCrossDomain = function(req, res, next) 
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
;

app.configure(function() 
  app.set('port', process.env.PORT || 3000);
  app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
  app.use(express.bodyParser()),
          app.use(allowCrossDomain);
  app.use(express.static(path.join(__dirname, 'public')));
);

app.get('/api/brands', brands.findAll);

http.createServer(app).listen(app.get('port'), function() 
  console.log("Express server listening on port " + app.get('port'));
);

motoads/server/routes/brands.js

exports.findAll = function(req, res) 
  var fs = require('fs');
  var file = './server/data/brands.json';

  fs.readFile(file, 'utf8', function(err, data) 
    if (err) 
      throw err;
    
    res.send(JSON.parse(data));
  );
;

motoads/server/data/brands.json

[
  "name": "Audi", "models": ["name": "A1", "name": "A3", "name": "A4"],
  "name": "BMW", "models": ["name": "Series 3", "name": "Series 5", "name": "Series 7"],
  "name": "Citroen", "models": ["name": "C1", "name": "C2", "name": "C3"],
  "name": "Dacia", "models": ["name": "Duster", "name": "Logan", "name": "Sandero"]
]

【讨论】:

以上是关于跨域ajax调用失败-Angular.js节点js + express的主要内容,如果未能解决你的问题,请参考以下文章

Angular.js xhr.open() 抛出“拒绝访问”错误

识别 ASP.NET MVC 代码中的 Angular js AJAX 调用

Jquery $.ajax 在跨域调用的 IE 中失败

在 Internet Explorer 上使用 Windows 身份验证通过 SSL 进行跨域 ajax 调用失败

如何解决IE8下Ajax调用时跨域的问题

关于angular.js请求数据的跨域问题