嘿,我正在尝试使用 express 和 Node 发送发布请求,这是我的代码。
index.html
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="/form" method="POST" enctype="multipart/form-data">
<input type="text" name="imagename"></input>
<input type="submit" name="submit" value="submit"></input>
</form>
</body>
</html>
我的 app.js 文件如下:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/form', function(req, res){
res.setHeader('Content-Type', 'application/json');
setTimeout(function(){
res.send(JSON.stringify({
imagename: req.body.imagename || null
}));
}, 1000);
});
现在我应该将输出作为图像名称://如果为真或为空,则在表单中添加值。而且我总是得到一个空值。我试图记录 req.body.imagename 的值,但我得到的是未定义的值,而不是我在表单中插入的值。如有任何帮助,我们将不胜感激。
最佳答案
您必须将 body-parser
添加到您的 Express 应用中。
var app = express();
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
但是,我看到您已经使用 enctype='multipart/formdata'
声明了您的表单。这通常用于文件上传,如果它真的是你想要的,你将需要使用 another parser
关于javascript - 在 Node.JS 中获取 http post 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45017717/