I'm向节点服务器发送了一个文件,它给了我404状态错误

I'm sending a file to node server it gives me 404 state error

本文关键字:文件 一个 错误 状态 节点 服务器      更新时间:2023-09-26

我的HTML文件如下所示,

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>file</title>
</head>
<body>
<form method="post" action="/getusrfile" enctype='multipart/form-data'>
    <input type="file" name="fil" >
    <button type="submit">
        sub
    </button>
</form>
</body>
</html>

我正在使用节点,表示为以下

app.post("/getusrfile",function(req,res){
    console.log("came to server");// prints this
    console.log(req.files);//prints undefined
    //console.log(JSON.stringify(req.files.fil));
    fs.readFile(req.files.fil, function (err, data) {
        // ...
        var newPath = __dirname + "/../public/uploadedFileName";
        fs.writeFile(newPath, data, function (err) {
            console.log(err);
            res.send(err);
        });
    });
});

它打印到服务器,但没有在服务器上创建任何文件/目录。响应为"Cannot POST/getusrfile",状态为404。

和req.files打印未定义的

如何使其发挥作用?

第一个

    $ npm install --save multer

然后在app.post函数之前添加multer中间件:

    app.use(require('multer')({dest : __dirname }));
    app.post("/getusrfile",function(req,res){
      var filePath = req.files.fil.path;
      fs.readFile(filePath, function (err, data) {
        // ...  
      });
    });

测试:

   it('should respond "OK 200" to POST request with file payload',function(done){
        var filePath = path.join(__dirname,'test.txt');
        request(app)
        .post('/getusrfile')
        .attach('fil',filePath)
        .expect(200)
        .end(function(err,res){
            expect(err).to.not.exist;
            done();
        });
    });