javascript - 向angular js发送http请求

标签 javascript html angularjs http p2p

我知道如何使用 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 的操作不应发生在服务器端。我将 IPFSnode jsangular 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/

相关文章:

angularjs 返回上一页 state.go stateParams

javascript - angularjs fomly - 模板中的变量错误

javascript - React/redux 上一个状态随着下一个全州范围不断变化

javascript - 为什么这个旋转横幅的导航按钮不起作用?

javascript - 在 iOS Safari 上打开文件/图像选择器时,现有异步请求因网络错误而失败

c# - 如何选择特定图像并从特定网址保存? (内有说明)

html - Div-container 在调整浏览器窗口大小时移动

css - 为什么我的文字溢出

javascript - AngularJS 自定义更改无法正常工作

html - flexbox/网格布局中的最后边距/填充折叠