2015-12-05 25 views
0

我想從Ionic向節點服務器發送數據。然後用節點更改數據並將其他數據返回給Ionic。從節點服務器返回數據到Ionic(Angularjs)客戶端

但我現在不能如何將數據返回到離子。使用離子(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); 

日誌輸出

[email protected]:~/svn/nodejs$ node server.js 
Listening at http://127.0.0.1:3000 
POST 
Partial body: "Test" 
Body: "Test" 
+0

在客戶端代碼中,http函數必須採用一個'回調函數',它會隨服務器的響應一起提供。 –

回答

0

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回調。

+0

而我該如何創建服務器端代碼?這是任何時候返回錯誤。 –

+0

你可以把服務器端的日誌看看發生了什麼? –

+0

它可能是本地環境中的CORS,http://blog.ionic.io/handling-cors-issues-in-ionic/ –

相關問題