@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
}
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }) };
@Injectable({ providedIn: 'root' }) export class ApiService { apiUrl = 'http://localhost:8080/api';
constructor(private http: HttpClient) {}
getUsers(): Observable${this.apiUrl}/users
, httpOptions);
}
}
在上面的代码中,我们在httpOptions中添加了Access-Control-Allow-Origin标头,这样就可以解决CORS问题。