代码之家  ›  专栏  ›  技术社区  ›  Alex

将res.json()表示为角度$http.get()格式问题

  •  1
  • Alex  · 技术社区  · 7 年前

    如何从中获取数据 res.json() [服务器]中的响应对象 $http.get() [控制器]?

    我觉得这和 content-type 因为我不想手动键入 $scope.message = data.data.message;

    我在玩弄平均值堆栈,并尝试将数据从express显示为angular ng-bind .

    Server.js 使用 .get() /api 用简单对象响应的路由 res.json({ message : 'Hello World' }) 如下图所示:

    ...
    // Server frontend view
    app.use(express.static(__dirname + '/public'));
    
    // Configure bodyParser
    app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
    app.use(bodyParser.json());                                     // parse application/json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
    
    // Specify backend route
    router.get('/api', (req, res) => {
      res.json({message : 'Hello World'});
    });
    ...
    


    角度控制器使用一个简单的 $http.get('/api/) 如下图所示检索数据:
    ...
    $http.get('/api')
      .then(data => {
        $scope.message = data;
          console.log('Data: ' + data);
       }, err => {
         console.log('Error: ' + err);
       });
    ...
    


    当我测试的时候 localhost:port/api ,我明白了。 {message:'Hello World'} ,请 当我使用 localhost:port 这是我的角度视图,我看到这个数据:

    “data”:“message”:“你好” world“”,“status”:200,“config”:“method”:“get”,“transformrequest”:[null],“transformResponse”:[null],“jsonpcallbackparam”:“callback”,“url”:“/api”,“headers”:“accept”:“application/json, 文本/纯文本, / “,”“statusText”:“确定”,“xhrstatus”:“完成”

    1 回复  |  直到 7 年前
        1
  •  3
  •   Estus Flask    7 年前

    data parameter is fact response object ,and response body is available as data property.应该是:

    $http.get('/api')
    。然后(数据)=>。{
    $scope.message=数据;
    console.log('数据:'+数据);
    },错误=>。{
    console.log('错误:'+err);
    })(二)
    
    响应对象,响应主体可用为数据属性。应该是:

    $http.get('/api')
      .then(({ data }) => {
        $scope.message = data;
          console.log('Data: ' + data);
       }, err => {
         console.log('Error: ' + err);
       });
    
    推荐文章