Gui*_*ume 5 spring-boot angular5
我正在使用 Angular 学习 Spring Boot,我正在尝试启动并运行我的第一个应用程序,阅读以下博客:
http://mydevgeek.com/angular-4-crud-application-with-spring-boot-rest-service-part-2/
https://dzone.com/articles/build-a-basic-crud-app-with-angular-50-and-spring
我设法在 8080 端口上使用 spring boot 使应用程序正常工作,并且它按预期工作。但是,当我尝试让它与 Angular 一起使用时,出现以下错误:
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
core.js:3675
ERROR
{…}
error: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest
__zone_symbol__errorfalse: null
__zone_symbol__loadfalse: null
__zone_symbol__xhrListener: function scheduleTask/target[XHR_LISTENER]()
__zone_symbol__xhrSync: false
__zone_symbol__xhrTask: Object { runCount: 0, _state: "notScheduled", type: "macroTask", … }
__zone_symbol__xhrURL: "//localhost:8080/cool-cars"
mozAnon: false
mozSystem: false
readyState: 4
response: ""
responseText: ""
responseType: "text"
responseURL: ""
status: 0
statusText: ""
timeout: 0
upload: XMLHttpRequestUpload { }
withCredentials: false
__proto__: XMLHttpRequestPrototype { open: patchMethod/proto[name](), setRequestHeader: setRequestHeader(), send: patchMethod/proto[name](), … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest
__zone_symbol__errorfalse: null
__zone_symbol__loadfalse: null
__zone_symbol__xhrListener: function scheduleTask/target[XHR_LISTENER]()
__zone_symbol__xhrSync: false
__zone_symbol__xhrTask: Object { runCount: 0, _state: "notScheduled", type: "macroTask", … }
__zone_symbol__xhrURL: "//localhost:8080/cool-cars"
mozAnon: false
mozSystem: false
readyState: 4
response: ""
responseText: ""
responseType: "text"
responseURL: ""
status: 0
statusText: ""
timeout: 0
upload: XMLHttpRequestUpload { }
withCredentials: false
__proto__: XMLHttpRequestPrototype { open: patchMethod/proto[name](), setRequestHeader: setRequestHeader(), send: patchMethod/proto[name](), … }
target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "//localhost:8080/cool-cars", readyState: 4, … }
timeStamp: 5395.150856236699
total: 0
type: "error"
__proto__: ProgressEventPrototype { lengthComputable: Getter, loaded: Getter, total: Getter, … }
headers: Object { normalizedNames: Map, lazyUpdate: null, headers: Map }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
__proto__: Object { constructor: HttpErrorResponse() }
Run Code Online (Sandbox Code Playgroud)
当我查看网络选项卡时,我看到以下信息:
标头:接受
应用程序/json,文本/纯文本,/
接受编码gzip,放气接受语言fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3 Connection
keep-alive Host
localhost :8080
请求地址:http://localhost:8080/cool-cars 请求方式:GET
但没有回应。似乎请求超时。
Chrome 网络标签显示:
Request URL:http://localhost:8080/cool-cars
Referrer Policy:no-referrer-when-downgrade
Provisional headers are shown
Accept:application/json, text/plain, */*
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
Run Code Online (Sandbox Code Playgroud)
我的 Java 课程:
车类:
import lombok.*;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Entity;
@Entity
@Getter @Setter
@NoArgsConstructor
@ToString @EqualsAndHashCode
public class Car {
@Id @GeneratedValue
private Long id;
private @NonNull String name;
}
Run Code Online (Sandbox Code Playgroud)
汽车仓库:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
@RepositoryRestResource
@CrossOrigin(origins = "http://localhost:4200")
public interface CarRepository extends JpaRepository<Car, Long> {
}
Run Code Online (Sandbox Code Playgroud)
控制器:
import java.util.Collection;
import java.util.stream.Collectors;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/")
public class CoolCarController {
private CarRepository repository;
public CoolCarController(CarRepository repository) {
this.repository = repository;
}
@GetMapping("/cool-cars")
public Collection<Car> coolCars() {
return repository.findAll().stream()
.filter(this::isCool)
.collect(Collectors.toList());
}
private boolean isCool(Car car) {
return !car.getName().equals("AMC Gremlin") &&
!car.getName().equals("Triumph Stag") &&
!car.getName().equals("Ford Pinto") &&
!car.getName().equals("Yugo GV");
}
}
Run Code Online (Sandbox Code Playgroud)
应用类:
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
ApplicationRunner init(CarRepository repository) {
return args -> {
Stream.of("Ferrari", "Jaguar", "Porsche", "Lamborghini", "Bugatti",
"AMC Gremlin", "Triumph Stag", "Ford Pinto", "Yugo GV").forEach(name -> {
Car car = new Car();
car.setName(name);
repository.save(car);
});
repository.findAll().forEach(System.out::println);
};
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,CORS 是通过注释启用的。
在 Angular 中,我进行了以下更改。
汽车服务.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CarService {
constructor(private http: HttpClient) { }
getAll(): Observable<any> {
return this.http.get('//localhost:8080/cool-cars');
}
}
Run Code Online (Sandbox Code Playgroud)
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CarService } from './shared/car/car.service';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import {CarListComponent} from "./car-list/car-list.component";
@NgModule({
declarations: [
AppComponent,
CarListComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [CarService],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
汽车清单组件:
import { Component, OnInit } from '@angular/core';
import { CarService } from '../shared/car/car.service';
@Component({
selector: 'app-car-list',
templateUrl: './car-list.component.html',
styleUrls: ['./car-list.component.css']
})
export class CarListComponent implements OnInit {
cars: Array<any>;
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getAll().subscribe(data => {
this.cars = data;
});
}
}
Run Code Online (Sandbox Code Playgroud)
汽车列表组件html
<h2>Car List</h2>
<div *ngFor="let car of cars">
{{car.name}}
</div>
Run Code Online (Sandbox Code Playgroud)
我正在使用 IntelliJ。
我已经阅读了很多关于这个问题的内容,包括关于这个主题的类似问题,但我没有看到可以解决这个问题的答案(并且有相同的空响应)。非常感谢您的帮助!
| 归档时间: |
|
| 查看次数: |
4576 次 |
| 最近记录: |