美文网首页ng-alain
ng-alain跨域问题和自定义请求拦截

ng-alain跨域问题和自定义请求拦截

作者: 谢炳南 | 来源:发表于2018-12-15 16:07 被阅读0次

    ng-alain解决跨域问题并添加请求拦截

    1.根目录创建proxy.conf.json文件

    {
        "/api": {
            "target": "https://testapi.kemiandan.com",
            "secure": "false",
            "changeOrigin": true,
            "pathRewrite": {
                "^/api": ""
            }
        }
    }
    

    2.package.json文件里面start命令里面添加 --proxy-config proxy.conf.json

    "start": "npm run color-less && ng serve -o --proxy-config proxy.conf.json",
    

    3.打开app目录下的delon.module.ts 去除以下代码,不然跨域请求默认到本地_mock里

    // #region mock
    import { DelonMockModule } from '@delon/mock';
    import * as MOCKDATA from '../../_mock';
    import { environment } from '@env/environment';
    const MOCK_MODULES = !environment.production
      ? [DelonMockModule.forRoot({ data: MOCKDATA })]
      : [];
    // #endregion
    
    // mock
    ...MOCK_MODULES,
    

    4.在app目录下新建http-interceptors文件夹并新建base-interceptor.ts文件

    import { Injectable } from '@angular/core';
    import {
        HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,
        HttpErrorResponse
    } from '@angular/common/http';
    import { throwError } from 'rxjs'
    import { catchError, retry } from 'rxjs/operators';
    // import { environment } from '@env/environment.prod';
    import {environment} from '@env/environment';
    
    /*设置请求的基地址,方便替换*/
    const baseurl = environment.baseurl;
    
    @Injectable()
    export class BaseInterceptor implements HttpInterceptor {
    
        constructor() { }
        intercept(req, next: HttpHandler) {
            
            let newReq = req.clone({
                url: req.hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`,
            });
            let token = sessionStorage.getItem('token');
            newReq.headers = newReq.headers.set('token', token?token:"");
    
            // send cloned request with header to the next handler.
            return next.handle(newReq)
                .pipe(
                    /*失败时重试2次,可自由设置*/
                    retry(2),
                    /*捕获响应错误,可根据需要自行改写,我偷懒了,直接用的官方的*/
                    catchError(this.handleError)
                )
        }
    
        private handleError(error: HttpErrorResponse) {
            if (error.error instanceof ErrorEvent) {
                // A client-side or network error occurred. Handle it accordingly.
                console.error('An error occurred:', error.error.message);
            } else {
                // The backend returned an unsuccessful response code.
                // The response body may contain clues as to what went wrong,
                console.error(
                    `Backend returned code ${error.status}, ` +
                    `body was: ${error.error}`);
            }
            // return an observable with a user-facing error message
            return throwError(
                'Something bad happened; please try again later.');
        };
    }
    

    5.打开app目录下的app.module.ts
    const INTERCEPTOR_PROVIDES变量值为ng-algin默认的请求拦截,去掉替换成

    import {BaseInterceptor} from './http-interceptors/base-interceptor';
    const INTERCEPTOR_PROVIDES = [
        { provide: HTTP_INTERCEPTORS, useClass: BaseInterceptor, multi: true},
    ];
    

    6.项目启动时执行以下命令便可跨域且有请求拦截

    ng serve --proxy-config proxy.conf.json
    

    angular打包资源文件404

    打包命令执行

    ng build --base-href ./
    

    相关文章

      网友评论

        本文标题:ng-alain跨域问题和自定义请求拦截

        本文链接:https://www.haomeiwen.com/subject/tusahqtx.html