① Create folder "nodeDemo"
Create a new folder locally to store the project, and you can set a memorable name related to the project content
② Execute the command "npm init -y" - - - Create the "pakage.json" file
"npm init -y" can create a "pakage.json" file in one step, and
"npm init" can also create a "pakage.json" file, but you need to follow the prompts and enter information step by step to complete the creation
You can choose the creation method according to your needs
③ Execute commands in sequence:
"npm i ts-node -g" - - - Install ts-node, if you have already installed it, you don't need to execute this command "
npm i @types/node -D" - - - Install node declaration file
"npm i express -S" - - - Install express
"npm i @types/express -D" - - - Install express declaration file
"npm i axios -S" - - - Install axios
④ Create a new "index.ts" file
a. Import express, axios
import express, {
Express, Router, Request, Response} from 'express'
import axios from 'axios'
b. Create express service
const app:Express = express()
c. Create a router and mount it to the service
const router:Router = express.Router()
app.use('/api', router)
d. Set routing request interface data
router.get('/api/list',async (req:Request, res:Response) => {
const result = await axios.get('线上接口地址')
res.json({
data: result.data
})
})
e. Enable service monitoring
app.listen(666, () => {
console.log('success server http://localhost:666');
})
The complete code of index.ts is as follows:
import express, {
Express, Router, Request, Response} from 'express'
import axios from 'axios'
const app:Express = express()
const router:Router = express.Router()
app.use('/api', router)
router.get('/api/list',async (req:Request, res:Response) => {
const result = await axios.get('线上接口地址')
res.json({
data: result.data
})
})
app.listen(666, () => {
console.log('success server http://localhost:666');
})
⑤ Configure the "package.json" file and add the command to start the service
"scripts": {
"dev": "ts-node index.ts"
},
as the picture shows:
⑥ Enter "npm run dev" on the command line to start the service
After the startup is successful, a prompt as shown in the following figure will appear:
⑦ Access interface: You can enter the interface address in "postman" to test the interface request
eg: ‘http://localhost:3333/api/list’