我知道如何使用 angular js 向服务器发送 http 请求。返回 promise
后,我知道如何监听 response
并随后操作 ui。但是这种方法不能用于我的想法。
但是,我不知道如何向网站发送请求。
我有一个服务器 localhost:800/receiveData
,它接收一个 POST
请求,然后在 angularjs 站点上操作 UI 和 DoM
app.get('/', function(req,res){
res.sendFile(__dirname+'/index.html')
})
app.post('/receiveData', function(req,res){
var data = req.body.data
// assume data is a boolean
if(data){
//show a view in index.html using angular js or anything else
}else {
//show a different view in index.html
}
});
任何帮助将不胜感激。我需要 Angular js。拥有SPA势在必行。如果需要,我完全愿意添加额外的堆栈。
编辑:
正如 MarcoS 所指出的,理想情况下,对 dom 的操作不应发生在服务器端。我将 IPFS
与 node js
和 angular js
结合起来开发单页应用程序。使用 IPFS
设置的节点群与我的服务器有一条开放的通信线路(按设计)。基于通过通信线路发送到我的服务器的数据包,我需要通过 index.html
向用户传达消息。
最佳答案
我认为您的方法是错误的:在服务器端,您应该不操作 UI 和 DOM...
您应该只执行服务器 事件(更新数据库、发送电子邮件、...、返回静态 页面)。
然后您可以输出一个结果(JSON/XML/...格式)供您的客户端调用脚本读取。
在 OP 编辑之后,我的理解是他希望服务器推送到客户端。
要获得服务端推送,您应该在客户端上轮询。
在 Controller 中:
function getServerState(changeState) {
return $http.get("/receiveData").then(function(res) {
changeState(res.data); // notify the watcher
}).catch(function(e) {
/* handle errors here */
}).then(function() {
return getServerState(changeState); // poll again when done call
});
}
这样消费:
getServerState(function(status) {
$scope.foo = status; // changes to `foo` $scope variable will reflect instantly on the client
});
服务器端:
app.post('/receiveData', function(req, res) {
var data = req.body.data; // assume data is a boolean
res.end(JSON.stringify(data);
});
关于javascript - 向angular js发送http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348281/