Here is a series of articles that will allow you to create backend applications with NodeJS + Express.
This series is the continuation of my series on the basics of NodeJS. If you don't have basic knowledge of NodeJS read this the first article of the series.
Node.js is today a must, so it is essential for a developer to master it.
So I will publish a new article about every two days and little by little you will learn everything there is to know about Node.js + Espress
To not miss anything follow me on twitter: twitter.com/EricTheCoder_
JSON data from a data file
In a real world application, the data will not be send directly in the res.json(). The data will be read from some kind of database.
For the following exemples, we will create a text JSON database to help mimic a real world scenario
Create a file name data.js and copy/paste this code
const products = [
{ id: 1, name: 'iPhone', price: 800 },
{ id: 2, name: 'iPad', price: 650 },
{ id: 3, name: 'iWatch', price: 750 }
]
module.exports = products
Change the app.get() to send the products data
const express = require('express')
const app = express()
const products = require('./data.js')
app.listen(5000, () => {
console.log('server is listening on port 5000')
})
app.get('/api/products', (req, res) => {
res.json(products)
})
This code will return all the products content.
Sometime it could be handy to only return part of the products. For exemple some fields can be confidential.
Here a exemple returning everything except the price
app.get('/api/products', (req, res) => {
const partial_products = products.map(product => {
return { id: product.id, name: product.name }
})
res.json(partial_products)
})
Route parameters
What if you want to load only product with id 1. The convention want to route to be something like: api/products/1
Espress have a easy way to manage that kind of request
app.get('/api/products/:productID', (req, res) => {
const id = Number(req.params.productID)
const product = products.find(product => product.id === id)
res.json(product)
})
Note the :productID in the route url. The :productID is a wildcard to put the content following the 'api/products/' ex: api/products/1
The productID can be retrieve from your request with the req.params.productID
What append if the request contain a id not in the data. ex: 'api/products/1080' ? Nothing will be display.
By convention in that situation we send a 404 Not Found status
app.get('/api/products/:productID', (req, res) => {
const id = Number(req.params.productID)
const product = products.find(product => product.id === id)
if (!product) {
return res.status(404).send('Product not found')
}
res.json(product)
})
Query String
It is usual for an API to allow user sending search request. For exemple if a user want all the product that the name contain the word phone he can send this request
GET api/query/?name=phone
Like everything else, Express have an easy way to grab the data from the query string. We can use the "req.query" to retrieve the query string.
app.get('/api/query', (req, res) => {
const name = req.query.name.toLowerCase()
const products_result = products.filter(product => product.name.toLowerCase().includes(name))
if (products_result.length < 1) {
return res.status(200).send('No products matched your search')
}
res.json(products_result)
})
const name = req.query.name.toLowerCase() retrieved the query string named "name" from the URL and convert it to lower case.
Then we only have to filter our products list on that value to get the products_results
Conclusion
That's all for today, follow me on twitter: twitter.com/EricTheCoder_ to be notified of the publication of the next article (within two days).