解决Angular与Java后端返回CORS(跨域资源共享)错误的方法如下:
import org.springframework.web.bind.annotation.CrossOrigin;
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/api/data")
public ResponseEntity
在上面的示例中,我们允许来自"http://localhost:4200"域名的请求访问该接口。
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getData() {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.get('http://localhost:8080/api/data', { headers: headers });
}
}
在上面的示例中,我们设置了"Content-Type"头信息,并将其发送到"http://localhost:8080/api/data"接口。
spring.mvc.dispatch-options-request=true
spring.web.cors.allowed-origins=http://localhost:4200
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=Content-Type
application.yml:
spring:
mvc:
dispatch-options-request: true
web:
cors:
allowed-origins: http://localhost:4200
allowed-methods: GET,POST,PUT,DELETE
allowed-headers: Content-Type
以上配置允许来自"http://localhost:4200"域名的请求访问Java后端,并允许GET、POST、PUT和DELETE方法。
请注意,这些解决方法仅提供了一种应对CORS错误的方式,具体的解决方法可能因你的应用程序和服务器配置而有所不同。
下一篇:Angular预检请求添加头部