Angular: 配置 proxy 解决跨域

发布时间:2024年01月23日

配置 proxy.config.json

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

在 angular.json 中配置 proxy

"serve": {
     "builder": "@angular-devkit/build-angular:dev-server",
     "options": {
       "browserTarget": "min-wyy:build",
       "proxyConfig": "proxy.config.json"
     },
	...
}

service.module.ts

import { isPlatformBrowser } from '@angular/common';
import { InjectionToken, NgModule, PLATFORM_ID } from '@angular/core';
import { httpInterceptorProvides } from './http-interceptors';


export const API_CONFIG = new InjectionToken('ApiConfigToken');
export const WINDOW = new InjectionToken('WindowToken');


@NgModule({
  declarations: [],
  imports: [
    
  ],
  providers: [
    {
      provide: API_CONFIG,
      useValue: '/api/' // useValue: 'http://localhost:3000/'
    },
    ...
  ]
})
export class ServicesModule { }


文章来源:https://blog.csdn.net/Lm_choose_live/article/details/135749265
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。