angularjs - Node Express 不是重定向,而是返回一个字符串

标签 angularjs node.js express

我是 Node 和 Angular 的新手,试图找出如何重定向错误的请求。 Node 本质上是 RESTful API 的代理。目前,weather.error 被填充为 Bad Request。重定向到/public/400.html

服务器调用:

app.get('/currently', function(request, response) {
    var options = {
        exclude: 'minutely,hourly,daily,flags,alerts'
    };
    forecast.get(request.query.latitude, request.query.longitude, options, function(err, res, data) {
        if (err) {
            console.log('Error in request. \nLatitude: ' + request.query.latitude + '\nLongitude: ' + request.query.longitude);
            var status = data.split('<title>')[1].split(' ')[0]
            if (status === '404') {
                response.status(400).sendFile(__dirname + '/public/images/404/404-' + Math.floor((Math.random() * 3) + 1) + '.jpg');
            } else if (status === '400') {
                response.redirect(400, '/public/400.html');
            } else {
                response.status(parseInt(status)).end();
            }
        } else {
            response.send(JSON.stringify(data));
        }
    });
});

Controller :

angular.module('myApp.weather', [
    'ui.router'
])
  .config(function($stateProvider) {
      $stateProvider
          .state('weather', {
              url: '/weather',
              templateUrl: 'app/weather/weather.tmpl.html',
              controller: 'WeatherController as weather'
          });
  }).controller('WeatherController', function($http, $location) {
      var weather = this;
      weather.latitude = '';
      weather.longitude = '';

      weather.getCurrentWeatherByLatLon = function(latitude, longitude) {
          $http.get('/currently?latitude=' + latitude + '&longitude=' + longitude)
              .success(function(data, status, headers, config) {
                  weather.data = data;
              })
              .error(function(data, status, headers, config) {//I don't think this should be necessary if I'm handling it in the sever
                  weather.error = data;
                  if(data.indexOf('Bad Request') >= 0) { 
                      console.log('Bad Request')
                      $location.path('/public/400.html'); //doesn't navigate anywhere
                  }
              })
              ;
      };

----------------------------编辑-------------- ----------

我已将服务器调用更改为:

app.get('/currently', function(request, response) {
    var options = {
        exclude: 'minutely,hourly,daily,flags,alerts'
    };
    forecast.get(request.query.latitude, request.query.longitude, options, function(err, res, data) {
        if (err) {
            console.log('Error in request. \nLatitude: ' + request.query.latitude + '\nLongitude: ' + request.query.longitude);
            var status = data.split('<title>')[1].split(' ')[0]
            response.status(status).send();
        } else {
            response.send(JSON.stringify(data));
        }
    });
});

我的 Controller 中的函数是:

weather.getCurrentWeatherByLatLon = function(latitude, longitude) {
    $http.get('/currently?latitude=' + latitude + '&longitude=' + longitude)
        .success(function(data, status, headers, config) {
            weather.data = data; // this callback will be called asynchronously
                // when the response is available
        })
        .error(function(data, status, headers, config) {
            weather.error = status
            if (status == 400) {
                console.log('in 400');
                $location.url('/public/400.html');
            } else if (status == 404) {                              
                console.log('in 404');
                $location.url('/public/404.html');
            }
        });
};

最佳答案

您无法重定向 ajax 调用。使用 response.redirect(400, '/public/400.html') 进行的重定向只是带有“特殊” header 的 HTTP 响应,ajax 不支持这一点。

如果您不想处理请求问题,请返回状态或类似内容并在客户端上处理。

关于angularjs - Node Express 不是重定向,而是返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018526/

相关文章:

javascript - Pino 错误日志为空,尽管错误对象包含信息

javascript - 等待 ".then"解决

javascript - Angular 选择默认选项

javascript - Angularjs 的 ng-click 按钮功能

javascript - 即使在我的服务器上的简单情况下,Express.js 路由器也无法工作

javascript - 如何将HTML数据从 Node js发送到前端?

javascript - 使用 Supertest,我可以创建一个默认设置一些 header 的替代请求吗?

javascript - 出现错误 - "Argument ' myCtrl' 不是函数,未定义”

android - 使用 jpm-mobile 在 Android 上运行 Firefox 插件

javascript - 返回 Mongoose 模型函数的结果