As NodeJS has evolved and is now widely known, it has become a must-have skill for front-end developers. NodeJS will not be covered in this article. If you are interested, visit NodeJS’s official website, Wikipedia
This article is to develop a server application using NodeJS+Express, a flexible Node.js Web application framework that keeps the scale to a minimum and provides a powerful set of capabilities for Web and mobile applications. See: official website
I. Preparatory Work
First, you need to install the NodeJS environment, which is not covered here. 1
npm install express -g
npm install express-generator -gCopy the code
2. Initialize the project
CD /Users/SPRINT/Desktop Go to the Desktop Express project nameCopy the code
The project name we specify is APIServer, from which we can see that we are a mock server API and here we will provide an interface to get user details and output JSON data.
Initialize the project
You see two commands output at the end of the terminal
Install dependencies: $CD APIServer &&npm install $DEBUG=APIServer:* NPM start // tells us to start serverCopy the code
Run the following command:
CD APIServer // Go to the root directory of the project. 2. NPM install // Install dependenciesCopy the code
Let’s go back to the desktop and you’ll see an APIServer directory that I’ve opened here using Sublime Text
APIServer
/bin: used to start the application (server) /public: used to store static resource directories /routes: used to determine how the application responds to client requests to a particular endpoint. This contains a URI (or path) and a specific HTTP request method (GET, POST, etc.). Each route can have one or more handler functions that are executed when the route matches. Jade directory app.js program main file This is the entry for the server to start
2 Starting the Server
Start the server first
NPM start // Start the serverCopy the code
Server startup
After the startup is complete, the terminal will output node./bin/ WWW to access http://localhost:3000/ in the browser
Browser output
Three Basic Use
Open app.js and here’s the main code
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var app = express(); / / / = = = = = = = routing information (interface address) in. / routes directory = = = = = = = = = = = / / var routes = the require ('. / routes/index); //home page var users = require('./routes/users'); Use ('/', routes); // add routes to app. Use ('/users', users); / / / / / registered users in the app interface = = = = = = = routing information (interface address introduced = = = = = = = = = = = / / / / / = = = = = = = templates = = = = = = = = = = = / / / / the view engine setup app. Set (' views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); ///======= Template end ===========//Copy the code
When we visit http://localhost:3000/ in a browser, we call the interface in index. We open index.js to see the definition of this interface:
var express = require('express'); var router = express.Router(); /* get home page. */ router. Get ('/', function(req, res, next) {res.render('index', {title: 'Express' }); }); module.exports = router;Copy the code
The basic format for defining a route is:
app.METHOD(PATH, HANDLER)Copy the code
Where: App is an instance of Express. METHOD is the HTTP request METHOD. PATH is the PATH on the server. HANDLER is a function that is executed when a route is matched. The above definition represents a response to a GET request on the root route (/) (the home page of the application) :
Is that clear?
What if we want to implement an interface to get user information? Simply create a user.js file in the Routes directory with the following contents: Define a user model
function User() {
this.name;
this.city;
this.age;
}
module.exports = User;Copy the code
User
Switch to the users.js file to add at the top of the file
var URL = require('url');Copy the code
And continue adding the following:
router.get('/getUserInfo', function(req, res, next) { var user = new User(); var params = URL.parse(req.url, true).query; if(params.id == '1') { user.name = "ligh"; user.age = "1"; User. city = "Beijing "; }else{ user.name = "SPTING"; user.age = "1"; User. city = "hangzhou "; } var response = {status:1,data:user}; res.send(JSON.stringify(response)); });Copy the code
Explain the main points:
Parse (req.url, true).query; require('url') var params = url.parse (req.url, true).query;Copy the code
getUserInfo API
Since the users.js routing information has been registered in app.js stop server restart server can be directly accessed
Call way http://localhost:3000/users/getUserInfo? Id = 1 or http://localhost:3000/users/getUserInfo? id=2
The response data
Have you noticed that we are accessing users/getUserInfo? Id =1 instead of root because we register app.js as app.use(‘/users’, users); Use (‘/ MSGS ‘, MSGS); use(‘/ MSGS ‘, MSGS); Call the way to http://localhost:3000/msgs/getUserMsgs? id=1
NodeJS has the ability to access mysql but is not the scope of this article
OK, I think getting started is enough
Welcome to follow personal public account: DevTipss
DevTipss