技术:Spring Boot,Angular4
我可以使用Postman发送POST请求,但在使用Angular4时,我收到XMLHttpRequest错误:
选项
http://localhost:9020/room/reservation/v1/
404()XMLHttpRequest无法加载http://localhost:9020/room/reservation/v1/。预检的响应具有无效的HTTP状态代码404
http://localhost:9020/room/reservation/v1
ReserveRoomRequest {roomId: 1, checkin: "2017-09-26", checkout: "2017-09-26"}
checkin
:
"2017-09-26"
checkout
:
"2017-09-26"
roomId
:
1
__proto__
:
Object
RequestOptions {method: 1, headers: Headers, body: null, url: null, params: undefined, …}
body
:
null
headers
:
Headers
_headers
:
Map(1)
size
:
(...)
__proto__
:
Map
[[Entries]]
:
Array(1)
0
:
{"content-type" => Array(1)}
key
:
"content-type"
value
:
["application/json"]
length
:
1
_normalizedNames
:
Map(1) {"content-type" => "Content-Type"}
__proto__
:
Object
method
:
1
params
:
undefined
responseType
:
null
search
:
(...)
url
:
null
withCredentials
:
null
__proto__
:
Object
zone.js:2744 OPTIONS http://localhost:9020/room/reservation/v1/ 404 ()
scheduleTask @ zone.js:2744
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ zone.js:301
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:405
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:236
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:259
(anonymous) @ zone.js:2769
proto.(anonymous function) @ zone.js:1274
(anonymous) @ http.es5.js:1275
webpackJsonp.../../../../rxjs/Observable.js.Observable._trySubscribe @ Observable.js:171
webpackJsonp.../../../../rxjs/Observable.js.Observable.subscribe @ Observable.js:159
webpackJsonp.../../../../../src/app/app.component.ts.AppComponent.createReservation @ app.component.ts:75
webpackJsonp.../../../../../src/app/app.component.ts.AppComponent.reserveRoom @ app.component.ts:56
(anonymous) @ AppComponent.html:82
handleEvent @ core.es5.js:12022
callWithDebugContext @ core.es5.js:13486
debugHandleEvent @ core.es5.js:13074
dispatchEvent @ core.es5.js:8615
(anonymous) @ core.es5.js:9226
(anonymous) @ platform-browser.es5.js:2651
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:424
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask @ zone.js:192
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:499
invokeTask @ zone.js:1427
globalZoneAwareCallback @ zone.js:1445
localhost/:1 XMLHttpRequest cannot load http://localhost:9020/room/reservation/v1/. Response for preflight has invalid HTTP status code 404
Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers, …}
headers
:
Headers {_headers: Map(0), _normalizedNames: Map(0)}
ok
:
false
status
:
0
statusText
:
""
type
:
3
url
:
null
_body
:
ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
__proto__
:
Body
Angular4代码:
let bodyString = JSON.stringify( body );
let headers = new Headers( { 'Content-Type': 'application/json' } );
let options = new RequestOptions( { method: RequestMethod.Post, headers: headers } );
let requestArg: RequestOptionsArgs = { headers: headers, method: "POST" };
console.log(this.postUrl);
console.log(body);
console.log(options);
this.http.post( this.getUrl, body, requestArg )
.subscribe( res => console.log( res ),
err => console.log( err ));
Spring Boot Code:
注释:
@CrossOrigin(origins = {"*"}, maxAge = 4800, allowCredentials = "false")
Controller.java
@RequestMapping(path = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ReservationResponse> createReservation(@RequestBody ReservationRequest reservationRequest) {
ReservationEntity reservationEntity = conversionService.convert(reservationRequest, ReservationEntity.class);
reservationRepository.save(reservationEntity);
RoomEntity roomEntity = roomRepository.findById(reservationRequest.getRoomId());
roomEntity.addReservationEntity(reservationEntity);
roomRepository.save(roomEntity);
reservationEntity.setRoomEntity(roomEntity);
ReservationResponse reservationResponse = conversionService.convert(reservationEntity,
ReservationResponse.class);
return new ResponseEntity<>(reservationResponse, HttpStatus.CREATED);
}
AppConfiguration.java
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/info/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedHeaders("X-Auth-Token", "Content-Type")
.exposedHeaders("custom-header1", "custom-header2")
.allowCredentials(false)
.maxAge(4800);
}