首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在localhost上启用Spring和Angular 2之间的CORS

在localhost上启用Spring和Angular 2之间的CORS,可以通过以下步骤实现:

  1. CORS(跨源资源共享)是一种机制,用于允许不同源的网页请求访问当前源的资源。在Spring中,可以通过配置CORS过滤器来启用CORS。
  2. 首先,在Spring的配置文件中添加CORS过滤器的配置。可以使用以下代码示例:
代码语言:txt
复制
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200") // 允许访问的源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的HTTP方法
                .allowedHeaders("*") // 允许的请求头
                .allowCredentials(true); // 允许发送凭证信息(如Cookie)
    }
}

上述代码中,allowedOrigins指定了允许访问的源,这里设置为Angular应用的地址http://localhost:4200allowedMethods指定了允许的HTTP方法,这里设置为常用的GET、POST、PUT和DELETE。allowedHeaders指定了允许的请求头,这里设置为*表示允许所有请求头。allowCredentials设置为true表示允许发送凭证信息,如Cookie。

  1. 接下来,在Angular应用中配置CORS。在Angular的代码中,可以通过在请求头中添加Access-Control-Allow-Origin字段来实现CORS。
代码语言:txt
复制
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class MyService {

  constructor(private http: HttpClient) { }

  getData() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:8080' // 允许访问的源
    });

    return this.http.get('http://localhost:8080/api/data', { headers });
  }
}

上述代码中,Access-Control-Allow-Origin字段指定了允许访问的源,这里设置为Spring应用的地址http://localhost:8080

  1. 最后,确保Spring和Angular应用都在localhost上运行,并且分别监听不同的端口(如Spring应用监听8080端口,Angular应用监听4200端口)。这样,Angular应用就可以通过CORS访问Spring应用的资源了。

总结: 通过在Spring中配置CORS过滤器,并在Angular中添加请求头,可以在localhost上启用Spring和Angular 2之间的CORS。这样,Angular应用就可以跨域访问Spring应用的资源了。

腾讯云相关产品推荐:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版(CDB):https://cloud.tencent.com/product/cdb
  • 腾讯云CDN:https://cloud.tencent.com/product/cdn
  • 腾讯云API网关:https://cloud.tencent.com/product/apigateway
  • 腾讯云容器服务:https://cloud.tencent.com/product/ccs
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券