簡體   English   中英

在node.js中發布數據

[英]post data in node.js

我有一個HTML文件,其中包括:

<form method="post" action="localhost:3000/post">
   <input name="user[name]" type="text"/>
   <button type="submit">sub</button>
</form>

在我的節點app.js文件中,我寫了以下幾行來發布:

app.post("/post" ,function(req ,res ){
   console.log(req.body.user.name);
   res.send(req.body.user.name);
});

但是我無法發布該數據。

搜索之后,我發現必須將以下行添加到節點文件中:

var bodyParser = require('body-parser');
app.use(express.bodyParser());

我使用“ npm install body-parser”進行安裝。但是發生錯誤。

我怎樣才能解決這個問題?

如果您使用的是Express 4,bodyParser將不再與它捆綁在一起。 因此,您必須更改此行:

app.use(express.bodyParser());

有了這個:

app.use(bodyParser());

您可以在這里找到更多信息和示例:

https://github.com/expressjs/body-parser

對於服務器部分

如果您已經通過npm-install成功安裝了body-parser

在您的app.js中添加這些行應該可以工作

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

如果發出警告像

body-parser deprecated urlencoded: explicitly specify "extended: true" for extended parsing

使用以下

app.use(bodyParser.urlencoded({
   extended: true
}));

在您的客戶中

在您的HTML中,您說的是action="localhost:3000/post" 我認為這變成了

/ post,如果您必須在同一服務器上發出請求

要么

action =“ http:// localhost:3000 / post如果正在向其他服務器發出請求。

試試點喜歡這個

要嘗試安裝sudo,因為我發現安裝東西有時不存在問題:

sudo npm install body-parser

然后,在您的代碼中,如果以上沒有失敗,則可能是這樣:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM