Home  >  Article  >  Web Front-end  >  Use express to start server service method sharing

Use express to start server service method sharing

小云云
小云云Original
2018-02-06 11:48:231883browse

This article mainly shares with you how to use express to start a server service. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.

Install express

$ npm install express --save

In node.js, our most commonly used framework is express

Express It is a minimalist and flexible web application development framework based on the Node.js platform. It provides a series of powerful features to help you create various web and mobile device applications.

The first step

We need to reference this framework

let express=require('express');

The second step

We mount this framework on a variable to make it easier for us to call the express built-in method later

let app=express()

The third step

We want to monitor Our service port number

app.listen(8080)

-------------------------- -----------

Below I wrote some routes to match the path name requested by the front-end, and then return some strings to the front-end (because I used the res.end() method, It can only accept strings and buffers, so what I return here is a string)

app.get('path name', function)

The following is an example directly to explain each line of code

//引入express框架
let express=require('express');

//定义一个变量调用express各种方法
let app=express();
// app上有很多匹配请求方法 app.get app.post app.put app.delet
//app定义路由,其实也是一个函数,定义的很多方法
//当客户端以GET方式访问服务器/路由时候,会有那个函数进行处理
app.get('/',function (req,res) {
 res.end('home');
})
//当客户的以get方式访问服务器/user路径时候,会有那个函数进行处理
// 三部分 请求 路径 函数
app.get('/user',function (req,res) {
 res.end('user');
})
//app.all能匹配所有的方法,不管客户端请求过来的方法名是什么,都能匹配上
// 所以这个方法一定要放在最后面,意思上前面都没有匹配中后,匹配all
// * 代表所有的路径
app.all('*',function (req,res) {
 res.end('not found')
})
app.listen(8080);

/* listen源码
 var http = require('http');
 app.listen = function listen() {
 var server = http.createServer(this);
 return server.listen.apply(server, arguments);
 };
*
*
*
* */

Related recommendations:

Example analysis of simple encapsulation operation of nodejs based on mssql module to connect to sqlserver database

The above is the detailed content of Use express to start server service method sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn