解構賦值 const {X,X,X}

Barry YU
1 min readApr 9, 2020

--

「解構賦值 (Object Destructuring Assignment)」。

Destructuring 可以將陣列或物件中指定的資料取出成為變數。

很多宣告相同的時候, 可以放在同一個物件共同宣告

讓編碼看起來更簡潔.

我們就一次可以宣告多個變數// const name = req.body.name

// const email = req.body.email

// const password = req.body.password

// const password2 = req.body.password2

可以將所以綜合一起宣告(declared).

// const { name ,emal,password,password2 } = req.body

且它們的值都是從 req.body 取得

補充:

< req.body >:

簡單說是 XXX. josn讓model 可以互相讀取資料庫內容

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

This example shows how to use body-parsing middleware to populate req.body.

var app = require('express')();
var bodyParser = require('body-parser'); <== 安裝
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})

req.body 是Post 的request功能 .

所以要安裝:body-parser

npm install body-parser 

npm 安裝吧!!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response