본문 바로가기
창고 3/[Dev] My Readme

Node js 기초 2

by 부엉이의 정보 창고 2022. 1. 13.
728x90

Express

Middleware

Serving static webpages and assets could be simpler with express since it provides a middleware.

Middleware is a function that takes route handlers and adds information. Express provdies the middleware to manage static assets. Without this middleware, all the static assets would require corresponding routes.

// syntax : express.static(root + endpoint)
// Normal usage
app.use(express.static(__dirname + "/public")) // directory 'public' is a convention where static assets are kept. 

// Assets at public dir
app.use('/public', express.static(__dirname + "/public"))

Middleware function takes three arguments : 1) request object 2) response object 3) next function.

  • add information to request/response object
  • end cycle by sending a response or start next function in stack, calling the next.

Express evaluates functions in the order they appear in the code. Middleware shoule also be created before all the routes depending on it.

function (req, res, next) { 
    console.log("I am a middle ware")
    next()
}

Middleware chaining

Middleware can be chained inside route definition. Chaining middleware is useful to divide server operaions into more smaller units, increasing code reusuability.

For example,

app.get('/user', function(req, res, next) {
    // do something here
    console.log(req.user)
    next()
}, function(req, res) {
    res.send(req.user)
})

Writing basic routing

// route in Express : app.method(path, handler)
// app : Express object
// path : relatvie path on the server
// handler : function(req, res). A function called when the route is matched
app.get('/', function(req, res){
    res.sendFile(__dirname + '/views/index.html'); 
});

What is __dirname?(tab to unfold)__dirname is your project root path, provided by Node.js. It is a string that can be concatenated with other directory resources.

app.get('/json', function(req, res) {
    res.json( { "message" : "Hello json" } ) // This method closes the request-response loop, returning the data. 
    // then sets the appropriate headers to tell your browser that you are serving JSON, and sends the data back.
    // Note that despite the method being named json(), the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.
})

Route parameter

Getting route parameter is one way to get inputs from user. Route paramters are named segments of the URL, differentiated by slash. Each segment holds an actual value of the URL. For example,

route_path: '/user/:userId/book/:bookId'
actual_request_URL: '/user/546/book/6754'
req.params: {userId: '546', bookId: '6754'}

Approach route parameter with request.params.

app.get('/:userId/location', function(req, res){
    const { userId } = req.params
    res.json( {location : userId} )
})

Query parameter

Encoding data with query string is also a way to get inputs from user. Query string is differentiated with question mark in the format of field and value.

route_path: '/library'
actual_request_URL: '/library?userId=546&bookId=6754'
query string : '?userId=546&bookId=6754'
req.query: {userId: '546', bookId: '6754'}

Express breaks down the data from the query string and fills with req.query. For example,

app.get('/library', function(req, res){
    const userId = req.query.userId // find the 'userId' in HTTP GET request body 
    const bookId = req.query.bookId // find the 'bookId' in HTTP GET request body 

    res.json( { library : `${userId} ${bookId}` } )
})

Body Parser For Post Request

HTTP Post method is a default method used to send client data with HTML form. It is conventioinally used to create a new record in database.

  • Front End ===(send a encoded data with HTTP POST method) ==>
  • ====> Backend ===(decoding the data in request body with body parser)===>
  • ========> Database(saving the data)

These types of request, sending information to the database, the information is not presented in URL since it can contain user password or such things. Instead, the data is hidden in HTTP request body, which is a called payload, also.

What is a payload?

Quoted from Wikipedia - payload

In computing and telecommunications, the payload is the part of transmitted data that is the actual intended message. Headers and metadata are sent only to enable payload delivery.

In the context of a computer virus or worm, the payload is the portion of the malware which performs malicious action.

The term is borrowed from transportation, where payload refers to the part of the load that pays for transportation.

Http request body by default is encoded with urlencoded, which looks like the above query string. You can also implement this with Ajax in JSON format.

To parse the data from HTTP request body, install body parser with npm package. It allows to use middleware to decode the data in many formats.

const bodyParser = require('body-parser')

// case 1 : parse urlencoded data sent by POST request
app.use(bodyParser.urlencoded({extended : false})) // configuration option. If false, use querystring library by default, when true, use qs library for pasring.

app.post('/name', function(req, res){
    const firstName = req.body.first // find the 'first' in HTTP POST request body 
    const lastName = req.body.last // find the 'last' in HTTP POST request body 
    res.json( {name : `${firstName} ${lastName}`} )
})

// case 2 : parse JSON data sent by POST request
app.use(bodyParser.json())
 

Reference

728x90

'창고 3 > [Dev] My Readme' 카테고리의 다른 글

Learning React essentials 1  (0) 2022.01.18
Understanding asynchronous Javascript  (0) 2022.01.17
Node js 기초 1  (0) 2022.01.12
몽고 DB 기초 6  (0) 2022.01.11
몽고 DB 기초 5  (0) 2022.01.10

댓글


loading