我尝试将 vs code 中本地运行的 spring boot 与 stackblitz 中的 Angle 连接起来,它一直显示待处理状态,稍后显示在 net::error 上
springboot:v3.3.1 角17
后端网址是:
http://localhost:8080
对于 stackblitz:
https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io/
我声明了一个WebConfig文件
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
并在运行文件中
@SpringBootApplication
@ComponentScan(basePackages = "com.example.novelWebsite", basePackageClasses = WebConfig.class) // Add CorsConfig
public class NovelWebsiteApplication {
public static void main(String[] args) {
SpringApplication.run(NovelWebsiteApplication.class, args);
}
}
我也尝试了在控制器中声明的方法,但仍然失败
@RestController
// @CrossOrigin(origins = "https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io/")
public class HelloController {
@GetMapping("/")
// @CrossOrigin(origins = "https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io")
public String index() {
return "Greetings from Spring Boot!";
}
}
在 main.ts 中我添加了
bootstrapApplication(App, {
providers: \[provideAnimationsAsync(),
provideRouter(routes),
provideHttpClient()\]
});
我创建了 proxy.conf.json 文件
{ "api": "http://localhost:8080",
"secure": false,
"changeOrigin": true }
并将其放入 angular.json
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"development": {
"buildTarget": "demo:build:development",
** "proxyConfig": "proxy.conf.json" **
},
"production": {
"buildTarget": "demo:build:production"
}
},
"defaultConfiguration": "development" } },
这是服务代码
export class HelloService {
private apiURL = 'http://localhost:8080'; // Replace with your Spring Boot backend URL
constructor(private http: HttpClient) {}
getGreetings(): Observable\<string\> {
return this.http.get\<string\>(`${this.apiURL}`);
}
}
以及接收它的组件代码
ngOnInit() {
this.helloService.getGreetings().subscribe({
next: (response: string) => {
this.responseText = response;
},
error: (err) => {
console.error('Error fetching greetings:', err);
}
});
}
并以html显示
{{responseText}}
它回来了
Error fetching data: HttpErrorResponse {headers: _HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8080', ok: false, …}
在网络选项卡中它显示状态待定
我已经尝试修复它,但没有效果,我将不胜感激任何帮助,谢谢
我尝试了另一种方法,而不是使用本地后端和公共前端。我也使用 ngrok 公开了后端,并且它有效。记得删除 Angular 中的代理配置