Using npm init in the terminal will include creating a Package.json file for you.
It will ask for the name, version, description, entry point, test command, git repository, keywords, author, and license.
After creating the package.json it will look something like
{
"name": "entered-name",
"version": "1.0.0",
"description": "entered description",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "entered author name",
"license": "ISC"
}
After creating the package.json file you can start your project by writing npm start in the terminal instead of node server.js.
With node.js you can write javaScript into the terminal.
The HTTP Module
In server.js put import http from 'node:http'. You could write just import http from 'http', but it is best practice to include node as it tells the app that it is a node module not a javaScript module. This can speed up performance.
In the package.json file add "type": "module", to the object below "main".
Allows data to be transferred over the HTTP protocol.
Used to create servers.
Used to handle requests from clients.
Used to provide responses to requests.
import http from 'node:http'
const PORT = 8000
const server = http.createServer((request, response) => {
response.end('whatever')
})
server.listen(PORT, () => console.log(`server is running on port: ${PORT}`))
The end method response.end() sends data over HTTP and ends the response. To get a response you need to be running npm start
A 200 response is success!
The response object
Has methods which allow us to:
Specify content type
set status codes (200, 400 etc.)
provide content (html, JSON, images)
The write method
const server = http.createServer((req, res) => {
res.write('whatever')
res.end()
})
allows you to write seperately from ending. You do still need to end.
The Request Response Cycle
The client makes an HTTP request to the server and the server sends an HTTP response to the client.
Example API: Client makes HTTP request containing (Method: GET, Request Path: /api, and Data: query string/ path params) to the server.
The server handles the requestion which could include filtering data, throwing an error, and generating a response. That response is than
passed from the server containing the Resourse (JSON), Content-Type (application/json), the Status code (200, 404, etc.), and the Satus message
to the client.
The Request Object
Gives us access to the incoming request. The URL the client used, headers being sent, data being sent, and the method (GET, POST, DELETE).
const server = htt.createServer((req, res) => {
if (req.url === '/specific-url') {
res.write('specific to url')
}
res.end()
})
On the request you can get the url req.url,
Methods
non-exhastive list
GET
POST
DELETE
PUT
PATCH
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.end('This will be sent from the server if the request is a GET method.')
}
})
JSON
Human readble
HTTP is a text-based protocol. All data transferred between the client and the server must be in the form of strings.
To convert JSON to a string you can use stringify: JSON.stringify(dataToConvert)
Turning query params into an object:
const urlObj = new URL(req.url, `http://${req.headers.host}`)
will return an object including searchParams.
const queryObj = Object.fromEntries(urlObj.searchParams)
will return an object of the search params in the search query.