[英]post data in node.js
I have a HTML file that includes: 我有一个HTML文件,其中包括:
<form method="post" action="localhost:3000/post">
<input name="user[name]" type="text"/>
<button type="submit">sub</button>
</form>
And in my node app.js file I write this lines for posting: 在我的节点app.js文件中,我写了以下几行来发布:
app.post("/post" ,function(req ,res ){
console.log(req.body.user.name);
res.send(req.body.user.name);
});
But I can't post that data. 但是我无法发布该数据。
After searching I found that I have to add this lines to node files: 搜索之后,我发现必须将以下行添加到节点文件中:
var bodyParser = require('body-parser');
app.use(express.bodyParser());
I install it with "npm install body-parser".But an error occurs. 我使用“ npm install body-parser”进行安装。但是发生错误。
How can I fix this? 我怎样才能解决这个问题?
If you're using express 4, bodyParser is no longer bundled with it. 如果您使用的是Express 4,bodyParser将不再与它捆绑在一起。 So you have to change this line :
因此,您必须更改此行:
app.use(express.bodyParser());
With this one: 有了这个:
app.use(bodyParser());
You can find more informations and exemples here : 您可以在这里找到更多信息和示例:
https://github.com/expressjs/body-parser https://github.com/expressjs/body-parser
FOR SERVER PART 对于服务器部分
If you've installed body-parser
through npm-install
successfully. 如果您已经通过
npm-install
成功安装了body-parser
。
Adding these lines in you app.js should work 在您的app.js中添加这些行应该可以工作
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
If gives warning like 如果发出警告像
body-parser deprecated urlencoded: explicitly specify "extended: true" for extended parsing
use following 使用以下
app.use(bodyParser.urlencoded({
extended: true
}));
In Your Client 在您的客户中
In Your HTML you are saying that action="localhost:3000/post"
. 在您的HTML中,您说的是
action="localhost:3000/post"
。 I think this changed to 我认为这变成了
/post if you have to make request on same server / post,如果您必须在同一服务器上发出请求
OR 要么
action="http://localhost:3000/post If you are making request to some other server. action =“ http:// localhost:3000 / post如果正在向其他服务器发出请求。
Try something liek this 试试点喜欢这个
To install try with sudo as I have found issues installing things without such at times: 要尝试安装sudo,因为我发现安装东西有时不存在问题:
sudo npm install body-parser
Then in your code if the above hasn't failed, something lie this: 然后,在您的代码中,如果以上没有失败,则可能是这样:
var app = express().use(require('body-parser')());
app.post("/post" ,function(req ,res ){
console.log(req.body.user.name);
res.send(req.body.user.name);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.