2019-12-02 TypeScript 创建第一个后台项目

TypeScript 创建第一个后台项目

1.创建文件夹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.执行tsc编译

8.执行 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文件调用service

image.png

13.使用Rest client查看结果

image.png

14.配置脚本

image.png

15.配置launch.json

image.png

16.配置tasks.json

image.png
image.png
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容