Angular 7如何在预检后请求中添加Access-Control-Allow-Origin标头?

时间:2019-07-04 06:49:17

标签: java angular spring typescript

我正在尝试发送帖子,但出现以下错误:

2zone-evergreen.js:2952 OPTIONS http://localhost:8080/api/infotel/createOrganisme 403
scheduleTask @ zone-evergreen.js:2952
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
(anonymous) @ zone-evergreen.js:2985
proto.<computed> @ zone-evergreen.js:1428
(anonymous) @ http.js:2065
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
(anonymous) @ subscribeTo.js:20
subscribeToResult @ subscribeToResult.js:7
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ scalar.js:4
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
create @ create-organisme.component.ts:32
(anonymous) @ CreateOrganismeComponent.html:21
handleEvent @ core.js:34789
callWithDebugContext @ core.js:36407
debugHandleEvent @ core.js:36043
dispatchEvent @ core.js:22533
(anonymous) @ core.js:33721
(anonymous) @ platform-browser.js:1789
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:30885
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
Show 12 more frames
display:1 Access to XMLHttpRequest at 'http://localhost:8080/api/infotel/createOrganisme' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
core.js:7187 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/api/infotel/createOrganisme", ok: false, …}

这是Java后端控制器:

package com.infotel.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.infotel.dto.OrganismeDTO;
import com.infotel.service.OrganismeService;

@RestController
@RequestMapping("/api/infotel")
public class Controller {

    private final OrganismeService orgService;

    public Controller(OrganismeService orgService) {
        this.orgService=orgService;
    }

    @PostMapping("/createOrganisme")
    public ResponseEntity<?> create(@RequestBody OrganismeDTO org){
        System.out.println(org.toString());
        this.orgService.create(org);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        headers.add("Access-Control-Allow-Headers", "X-Requested-With,content-type");
        headers.add("Access-Control-Allow-Credentials", "true");
        return new ResponseEntity<>(headers,HttpStatus.CREATED);
    }

    @GetMapping("/getAllOrganismes")
    public ResponseEntity<?> getAll(){
        List<OrganismeDTO> orgs = this.orgService.getAll();
        for(OrganismeDTO o : orgs) {
            System.out.println(o.toString());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        return new ResponseEntity<>(orgs,headers, HttpStatus.OK);
    }

}

这是打字稿服务:

import { Injectable } from '@angular/core';
import { Organisme } from './organisme';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

@Injectable({
  providedIn: 'root'
})
export class OrganismeService {
  urlGetAll = 'http://localhost:8080/api/infotel/getAllOrganismes';
  urlCreate = 'http://localhost:8080/api/infotel/createOrganisme';

  constructor(private http: HttpClient) { }

  getOrganismes(): Observable<Organisme[]> {
    return this.http.get<Organisme[]>(this.urlGetAll);
  }

  create(org: Organisme): Observable<any>{
    httpOptions.headers.append('Access-Control-Allow-Origin', 'http://localhost:8080');
    httpOptions.headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    httpOptions.headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    httpOptions.headers.append('Access-Control-Allow-Credentials', 'true');
    return this.http.post(this.urlCreate, JSON.stringify(org), httpOptions);
  }
}

我在FRONT和BACK上都有标题,并且在get不会显示错误的情况下出现此错误。
我错过了什么还是做错了什么?
如果您需要更多信息,请询问我。

1 个答案:

答案 0 :(得分:0)

在服务器站点上使用@CrossOrigin(origins =“ http://localhost:9000”),这将在API级别启用CORS

package com.infotel.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.infotel.dto.OrganismeDTO;
import com.infotel.service.OrganismeService;

@CrossOrigin(origins = "http://localhost:9000")
@RestController
@RequestMapping("/api/infotel")
public class Controller {

private final OrganismeService orgService;

public Controller(OrganismeService orgService) {
    this.orgService=orgService;
}

@PostMapping("/createOrganisme")
public ResponseEntity<?> create(@RequestBody OrganismeDTO org){
    System.out.println(org.toString());
    this.orgService.create(org);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    headers.add("Access-Control-Allow-Headers", "X-Requested-With,content-type");
    headers.add("Access-Control-Allow-Credentials", "true");
    return new ResponseEntity<>(headers,HttpStatus.CREATED);
}

@GetMapping("/getAllOrganismes")
public ResponseEntity<?> getAll(){
    List<OrganismeDTO> orgs = this.orgService.getAll();
    for(OrganismeDTO o : orgs) {
        System.out.println(o.toString());
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    return new ResponseEntity<>(orgs,headers, HttpStatus.OK);
}

}

1)用您的开发环境主机名和端口替换源,或者您可以引用https://spring.io/guides/gs/rest-service-cors/

2)对于开发环境,您可以启用CORS google chrome插件,并在生产级别后启用 您将其放在同一域中,此问题将解决您的问题