TypeScript 創(chuàng)建第一個后臺項目
1.創(chuàng)建文件夾service_demo
2.npm init -y
3.tsc --init
4.修改配置文件package.json tsconfig.json
image.png
image.png
5.安裝庫
(tool)
npm i @types/koa -D
npm i @types/koa-router -D
npm i @types/node -D
npm i dotenv -D
npm i typescript -D
npm i nodemon -g
(dependency)
npm i axios
npm i koa
npm i koa-router
npm i rxjs
6.編寫hello world
image.png
7.執(zhí)行tsc編譯
8.執(zhí)行 node ./dist/main.js
9.配置本地項目env
image.png
10.配置本地項目config
image.png
11.使用上面配置的config
image.png
11.新建service
import axios, { AxiosInstance } from "axios";
import { config } from './config'
import { from } from "rxjs";
export class Service {
async combine() {
let result = await Promise.all([this.getNews(), this.getDiscover()]);
return {
'news': result[0],
'services': result[1]
};
}
async getDiscover() {
const host: string = config.discover_url as string;
try {
const client = this._axiosFactory(host);
const res = await client.get('/api/servicemanager/v0/discoverallservices/v1?region=cn&locale=zh-cn&client=IOS&brand=1', {
headers: {
'AppVersion': '10.3.0',
'AppKey': '51dee986-d5b2-4af1-b129-4eaedc6c32b6'
}
});
return res.data;
} catch (e) {
console.log(e);
}
}
async getNews() {
const host: string = config.news_url as string;
try {
const client = this._axiosFactory(host);
const res = await client.get('/api/news', {
headers: {
'X-AppKey': '2014_MyBMW837',
'x-btcapi-usid': '05e4c12d-2182-4862-928a-a08cc79a5dec'
}
});
return res.data;
} catch (e) {
console.log(e);
}
}
private _axiosFactory(host: string) {
return axios.create({
baseURL: host,
timeout: 30000
});
}
}
12.main.ts文件調(diào)用service
image.png
13.使用Rest client查看結(jié)果
image.png
14.配置腳本
image.png
15.配置launch.json
image.png
16.配置tasks.json
image.png
image.png
image.png