如何在angular和nodejs之间进行通信?

时间:2016-09-28 12:02:47

标签: javascript angularjs node.js

节点:app.js

var http = require("http");
var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/webshop';
var assert = require('assert');
mongoose.connect(url);
var products = mongoose.model('products', {
category: String,
type: String,
nme: String,
socket: Number,
clock: Number
});
app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});
app.use(express.static(__dirname + '/public'));
app.get('/products', function (req, res) {
    console.log("products");
    //Lets try to Find all products
    products.find(function (err, userObj) {
        if (err) {
            console.log(err);
            res.send(err);
        } else if (userObj) {
            console.log('Found:', userObj);
            res.json(userObj);
        //res.sendFile('views/aboutus.html', {root: 'public',data:userObj});
        } else {
            console.log('Products not found!');
        }
    });
});

products.html放在:

<!DOCTYPE html>
<html lang="en" ng-app="WebShop">
<head>
<meta charset="UTF-8">
<title>HELL</title>
<link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../bower_components/bootstrap/dist/css/bootstrap-theme.css" rel="stylesheet" type="text/css">
<link href="../stylesheets/style.css" rel="stylesheet">
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js">    </script>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../javascripts/app.js"></script>
</head>
<body ng-controller="mainController">
<table>
    <tr>
        <th>Category</th>
        <th>Type</th>
        <th>Name</th>
        <th>Socket</th>
        <th>Clock</th>
    </tr>
    <tr ng-repeat="product in products">
        <td>{{product.category}}</td>
        <td>{{product.type}}</td>
        <td>{{product.name}}</td>
        <td>{{product.socket}}</td>
        <td>{{product.clock}}</td>
    </tr>
</table>
</body>
</html>

角:

var app = angular.module('WebShop', ['ngResource', 'ngRoute']);
app.controller('mainController',function($scope, $http,Products) {
var products = Products.get();
console.log(products);
$http.get('/products')
    .success(function (data) {
        console.log("http get products");
        $scope.products = data;
        console.log(data);
    })
    .error(function (data) {
        console.log('Error: ' + data);
    });
});

app.factory('Products', ['$resource', function($resource) {
return $resource('/products', null,
    {
        'get': { method:'get' }
    });
}]);

所以我的问题是......当我去/产品我在网页上得到json对象...但我想使用angular和html文件...所以我想得到数组在角度,我想使用products.html在屏幕上查看....但现在我只看到对象数组。任何人都可以帮助我吗?我想我不理解AngularJs和NodeJS之间的沟通。我真的不知道如何发送角度以及如何使用带有角度标签/属性的html来显示结果。非常感谢!

2 个答案:

答案 0 :(得分:0)

您正在返回一个JSON用户对象作为响应并期望一个数组,JSON是javascript对象符号,所以它就像一个关联数组,似乎您使用mongoDB作为以JSON形式存储对象的数据库。如果要将JSON响应转换为属性数组作为键值对,可以参考: Converting JSON Object into Javascript array 或者可能会改变您在nodejs中编写服务的方式。 -V

答案 1 :(得分:0)

如果您将响应作为JSON返回,则可以使用以下示例。

app.js

var express = require('express');
var app = express();
var path = require('path');

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.get('/products', function (req, res) {
    var products = {
        1: {
            name: "Product 1",
            description: "This is an awesome product"
        },
        2: {
            name: "Product 2",
            description: "This is also an awesome product"
        }
   };
   res.writeHead(200, {"Content-Type": "application/json"});
   res.end(JSON.stringify(products));
});

app.listen(3000);

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular JS</title>
</head>
<body ng-app="myApp">
<div ng-controller="ProductController as product">
    <div ng-repeat="p in product">
        <h1>{{p.name}}</h1>
        <p>{{p.description}}</p>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
    var app = angular.module('myApp', []);
    app.controller('ProductController', function ($scope, $http) {
        $http.get("http://localhost:3000/products")
                .then(function (response) {
                    console.log(response.data);
                    $scope.product = response.data;
                });
    });
</script>
</body>
</html>

终于运行

node app.js

然后转到http://localhost:3000