1. 使用代理服务器
- 适用场景:开发阶段,方便快速解决跨域问题,无需后端配置。
- 实现步骤:
- 在Angular项目根目录创建
proxy.conf.json
文件。
- 配置代理规则,例如:
{
"/api": {
"target": "http://backend-server-url",
"secure": false,
"changeOrigin": true
}
}
- 在
package.json
的scripts
中添加"start": "ng serve --proxy-config proxy.conf.json"
。然后运行npm start
启动项目,此时所有以/api
开头的请求都会被代理到指定的后端服务器。
2. 后端配置CORS
- 适用场景:生产环境,通过后端允许特定来源的请求,一劳永逸解决跨域问题。
- 实现步骤:
- Node.js(Express):安装
cors
包npm install cors
,在服务器代码中引入并使用,例如:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
// 其他路由等配置
- Java(Spring Boot):在配置类中添加CORS配置,例如:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://angular-frontend-url")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}
3. JSONP(较少使用)
- 适用场景:仅适用于GET请求,用于一些不支持CORS的旧浏览器场景。
- 实现步骤:
- 在Angular中创建一个服务,例如
JsonpService
。
- 使用
HttpClient
的jsonp
方法发起请求,例如:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class JsonpService {
constructor(private http: HttpClient) {}
getJsonpData() {
let params = new HttpParams();
params = params.append('callback', 'JSONP_CALLBACK');
return this.http.jsonp('http://backend-url?', 'callback');
}
}
- 后端需要支持JSONP格式响应,将数据包裹在回调函数中返回。