Introduction to Node.js
Generally, we run Javascript in the browser. With Node.js we can run it on the computer.
Very convenient to set up a server.
There is a special object in JavaScript called Global Object (Global Object), it and all its properties can be accessed anywhere in the program, namely global variables.
In browser JavaScript, usually window is the global object, while the global object in Node.js is global. All global variables (except global itself) are attributes of the global object.
Running Script.js
ES2020:globalThis
globalThis is a global variable, corresponding to window in the browser, and global in other places.
Modules
The lower version of Node does not have Import and Export. Use require('path') and Module.exports
ES6 module
needs a version than versison12.0.
But it will report an error SyntaxError: Cannot use import statement outside a module
because it is not run as an ES file.
Solution 1:
Change the extension from .js to .mjs
Solution 2:
Add "type" in Package.json :{"Module"}
Run Package.json
Type of Module
There are three types of modules in Node. The
first one is a module created by yourself, which can be imported with require or import.
The second is the module that
is installed in Node in advance by build-in-module . For example,'fs', files can be read.
The third type is package from npm
nodemon to monitor any changes in the node.js application and automatically restart the service, which is very suitable for use in a development environment.
nodemon will monitor the files in the startup directory, and if any file changes, nodemon will automatically restart the node application.
"Start": "nodemon" then npm start
Building a server
If you want to use require(), you need to add the "type":{"module"} in package.json before, otherwise an error ReferenceError: require is not defined will be reported
In the HTTP connection, the message is divided into two types: request and response.
The request is equivalent to the request sent from the front end.
response is the returned content, which will be displayed on the web page
HTTP request method
Express.js
Express is a flexible Node.js web application development framework that keeps the smallest scale
Express middleware processes the request in the middle, and then performs the following steps after next().
RESTful API
The rest api is the best practice for separating the front and back ends. It is a set of standards or specifications for development, not a framework.
Get: receive the resource
Put: Change the state
Post:Create resource
Delete: remove the resource