如何通过http从服务器发送数据到客户端?

时间:2013-01-02 08:10:28

标签: ajax node.js http rest express

我想将服务器上文件的文件路径发送到客户端,以便使用媒体播放器播放。如何在客户端检索该字符串,以便在src元素的<video属性中连接它而不使用套接字?

服务器代码段:

res.set('content-type', 'text/plain');
res.send('/files/download.mp4');

3 个答案:

答案 0 :(得分:1)

这是您在没有任何框架的情况下向服务器发出请求的方式。 “/ path_to_page”是您设置为应该处理请求的页面的路径。

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path_to_page', true);
xhr.onload = function(e) {
if (this.status == 200) {
  console.log(this.responseText); // output will be "/files/download.mp4"
}
};

xhr.send();
}

您可能还想发送一些参数。

var formdata = new FormData();
formdata.append("param_name", "value");

所以你可能想要发送文件名等。

您只需要从第一个代码段更改2行。一个是

 xhr.open('POST', '/path_to_page', true); // set to post to send the params

 xhr.send(formdata); // send the params

要获取服务器上的参数,如果您使用快递,则它们位于req.body.param_name

答案 1 :(得分:0)

你使用哪个框架? 您可以在ajax中声明项目目录的基本路径,然后在文件中声明。

jQuery.ajax({
type: "GET",
url: "/files/download.mp4",

});

答案 2 :(得分:0)

由于您使用的是expressnode),因此您可以使用socket.io

服务器

var io = require('socket.io').listen(80),
    fs = require('fs');

io.sockets.on('connection', function (socket) {
   socket.on('download', function(req) {
      fs.readFile(req.path, function (err, data) {
         if (err) throw err;

         socket.emit('video', { video: data });
      });
   });
});

<强>客户端:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');

  ...      
  // request a download
  socket.emit('download', { path: '/files/download.mp4' });

  // receive a download
  socket.on('video', function (data) {
    // do sth with data.video;
  });
  ...
</script>

编辑:没有注意到您不想使用套接字。它仍然是一个可行的解决方案。