如何在post方法中传递值?

Jey*_*lai 0 javascript node.js express

我正在尝试使用nodejs从文件夹下载文件。使用get方法时一切正常。但是,当我尝试在后方法中发送文件名作为参数时,它显示“未定义”。

var download =req.body.download;

app.post("/hi", function (req, res)
 {
    res.download("./uploads/"+download+"");
});
Run Code Online (Sandbox Code Playgroud)

下载是我要传递文件名的参数

Tha*_*han 5

您应该使用中间件body-parser从请求主体中解析参数,并将其放入POST处理程序的范围内。要安装body-parser模块:

npm install body-parser --save
Run Code Online (Sandbox Code Playgroud)

如下更新代码:

npm install body-parser --save
Run Code Online (Sandbox Code Playgroud)

/hi使用body json 呼叫POST :

{
   "download": "test"
}
Run Code Online (Sandbox Code Playgroud)

更新:

Express 3中body-parser中间件被附加(内置)在express中。因此,不再需要安装它,只需要使用module声明如下:

const express = require('express')
const app = express()
const bodyParser = require("body-parser");

//Here we are configuring express to use body-parser as middle-ware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post("/hi", function (req, res) {
    var download = req.body.download;
    res.download("./uploads/"+download+"");
});
Run Code Online (Sandbox Code Playgroud)

供参考:Express中间件