![](/img/trans.png)
[英]How to add body in the request and get in second rest service in nodejs express
[英]How to extract body from request with express in NodeJs?
我正在使用Node.Js並為我的應用程序express
框架。
我建立HTML表單,但提交后無法收到API請求的form
數據。
我的HTML:
<form method="post" action="/create">
<input type="text" name="user.name" />
<input type="text" name="user.email" />
<input type="text" name="user.address.city" />
<input type="text" name="user.address.land" />
<input type="submit" value="Submit">
</form>
JSON對象應該在我的API中獲得:
{
"user": {
"name": "toto",
"email": "toto@mail.com",
"address": {
"city": "yyyyy",
"land": "zzzz"
}
}
}
如何使用Node.js Express 4做到這一點,還有另一個庫嗎?
您可以准備自己的中間件,該中間件使用body-parser的urlencoded()
解析傳入的表單數據,並將其轉換為結構化JSON:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
function setDeepValue(path, obj, value) {
const tokens = path.split('.');
const last = tokens.pop();
for (const token of tokens) {
if (!obj.hasOwnProperty(token)) {
obj[token] = {};
}
obj = obj[token];
}
obj[last] = value;
}
app.use(bodyParser.urlencoded(), function(req, res, next) {
let obj = {};
for (const key in req.body) {
setDeepValue(key, obj, req.body[key]);
}
req.body = obj;
next();
});
app.post('/create', function(req, res) {
console.log(req.body)
})
在您的HTML代碼中,您要發布到創建路徑。
因此,您需要創建一條路線
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.post('/create', function(req, res) {
console.log('----- MY BODY -----')
console.log(req.body)
// do something more clever
res.send('We posted to this route')
})
首先,我們需要express,然后我們需要body-parser,最后初始化我們的express應用。
然后,我們使用body-parser的json middlewere解析正文,以便我們可以在處理程序中輕松訪問它。
然后,我們定義到'/create'
的路由,該路由接受發布請求(請記住您的表單正在發布到此位置)。
我們的處理程序所做的全部工作就是console.log請求的主體,然后顯示消息我們已發布到此路由
遵循專門為指導新生而創建的本指南資料庫,以指導nodejs-frontend-sample-for-freshers
編輯:
您可以使用Ajax調用提交表單,這在單頁應用程序中也有幫助
客戶端JS:
function submit() {
// JavaScript uses `id` to fetch value
let email = $("#email").val(),
name = $("#name").val(),
city = $("#city").val(),
land = $("#land").val();
// Can validate each field here and show error like:
if ( validateEmail(email) ) {
$("#emailError").addClass("hide");
} else {
$("#emailError").removeClass("hide");
return;
}
// form request data, doing this will get you data in correct form at NodeJs API
let data = {
user: {
email,
name,
address: {
city,
land
}
}
};
$.ajax({
"url": "/create",
"method": "POST",
"data": data
})
.then( result => {
// On success empty all the input fields.
$("#email").val('');
$("#name").val('');
$("#city").val('');
$("#land").val('');
// Message to notify success submition
alert("Successfully added user.");
return;
})
.catch( err => {
// Notify in case some error occured
alert("An error occured.");
return;
});
}
// Validate Email based upon pattern
function validateEmail (email) {
if ( email && email.match(/^([A-z0-9_.]{2,})([@]{1})([A-z]{1,})([.]{1})([A-z.]{1,})*$/) ) {
return true;
}
return false;
}
HTML:
<form>
<input type="text" id="name" />
<input type="text" id="email" />
<span id="emailError" class="hide error">Valid Email Required</span>
<input type="text" id="city" />
<input type="text" id="land" />
<p onclick="submit()">Submit</p>
</form>
會建議您也使用cors.js
:
const cors = require('cors');
// Cross-Origin Resource Sharing
app.use(cors());
您可以通過兩種方式獲取對象:
1:不使用任何其他類似這樣的模塊
app.post('/create', function (request, response, next) {
let body = [];
request.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
console.log(body); // Your object
request.body = body; // Store object in request again
next();
});
}, (req, res) => {
console.log(req.body); // This will have your object
});
express
使用body-parser
: ```
// configure the app to use bodyParser() to extract body from request.
// parse urlencoded types to JSON
app.use(bodyParser.urlencoded({
extended: true
}));
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));
app.post('/create', function (request, response, next) {
console.log(request.body); // `body-parser did what I did earlier`
});
```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.