【问题标题】:Return Data from Node Server to Ionic(Angularjs) Client从节点服务器返回数据到 Ionic(Angularjs) 客户端
【发布时间】:2015-12-06 00:27:09
【问题描述】:

我想将数据从 Ionic 发送到节点服务器。然后使用节点更改数据并将其他数据返回给 Ionic。

但我现在不知道如何将数据返回给 ionic。


使用 Ionic (Angularjs) 的客户端:

$http({
  method: 'POST',
  url: 'http://127.0.0.1:3000',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  data: JSON.stringify("Test")
});

服务器节点

http = require('http');
server = http.createServer( function(req, res) {

  if (req.method == 'POST') {
    console.log("POST");
    var body = '';
    req.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    req.on('end', function () {
        console.log("Body: " + body);
    });
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('success');
    res.end('success');
  }else{
    console.log("GET");
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end("success");
  }
});

port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);

服务器的日志输出

ubuntu@ubuntu:~/svn/nodejs$ node server.js 
Listening at http://127.0.0.1:3000
POST
Partial body: "Test"
Body: "Test"

【问题讨论】:

  • 在客户端代码中,http 函数必须采用callback,这将来自服务器的响应。

标签: angularjs node.js ionic


【解决方案1】:

来自docs

General usage

The $http service is a function which takes a single argument — 
a configuration object — that is used to generate an HTTP request
and returns a promise.

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

$http 返回一个promise。 Promise 具有函数then,其前两个参数是来自服务器的successerror 回调。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 2016-07-02
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多