【问题标题】:How to recieve a file using request.get()?如何使用 request.get() 接收文件?
【发布时间】:2019-10-30 18:59:04
【问题描述】:

我正在编写一个用于提供和接收文件的服务器。它是用 node.js 编写的,使用 express.js。我还有一个客户端,也是用node写的,用来向服务器发送请求,接收服务器上的文件。

服务器端

const express = require("express");
const app = express();
const file = "./samplefiles/Helloworld.txt";

app.get("/", (res)=>{
    res.download(file);
});

module.exports = app; //this exports to server.js
const http = require("http");
const app = require("./app.js);
const port = 8080;

const server = http.createServer(app);

server.listen(port, () => {
    console.clear();
    console.log("server running");
})

客户端

const request = require("request");

request.get("http://localhost:8080/", (req, body) => {
    console.log(body);
    console.log(res);
});

如果我尝试通过浏览器访问它,系统会询问我想对文件做什么,它可以工作。但是,如果我运行我的客户端代码,它会打印正文和 res(为空)。我希望文件名及其内容在正文中,但只有文件的内容在正文中。

我想接收整个文件,有可能,或者至少得到它的名称,以便我可以在客户端“制作”它的副本。

【问题讨论】:

    标签: node.js express http request


    【解决方案1】:

    将服务器端的代码更改为:

    const port = 8080;
    const express = require("express");
    const app = express();
    const path = require('path');
    app.get("/", function(req, res){
        res.sendFile(path.join(__dirname, 'app.js'));
    });
    
    app.listen(port, () => {
    console.clear();
    console.log("server running");
    });
    

    将您的客户端代码更改为:

    var request = require('request');
    request('http://localhost:8080/', function (error, response, body) {
    console.log('error:', error); // Print the error if one occurred
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
    console.log('body:', body); // Print data of your file
    });
    

    您需要为客户端安装请求npm i request

    【讨论】:

      【解决方案2】:

      您可以使用 express 静态方法提供您想要的任何文件:

      app.use(express.static('public'))
      

      在这种情况下,只需将您要提供的所有文件放在名为 public 的文件夹中,然后您就可以通过 localhost:8080/Helloworld.txt 访问它。

      【讨论】:

      【解决方案3】:

      我最终解决了这个问题。

      我将文件名作为标题发送,因此能够使用正文信息和文件名标题创建我想要下载的文件的副本。

      【讨论】:

        猜你喜欢
        • 2013-12-12
        • 1970-01-01
        • 2019-04-09
        • 2018-02-25
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 2019-12-07
        • 1970-01-01
        相关资源
        最近更新 更多