java - Angular 7 如何将 Access-Control-Allow-Origin header 添加到预检发布请求中?

标签 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后端 Controller :

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);
    }

}

这是 typescript 服务:

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);
  }
}

我的标题位于正面和背面,但在 get 未显示错误的情况下出现此错误。
我错过了什么还是我做错了什么?
如果您需要更多信息,请询问我。

最佳答案

在服务器站点使用 @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 ) 将 origins 替换为您的开发环境主机名和端口,或者您可以引用 https://spring.io/guides/gs/rest-service-cors/

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

关于java - Angular 7 如何将 Access-Control-Allow-Origin header 添加到预检发布请求中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56882101/

相关文章:

java - 从 JSON 文件解析时无法从 JsonElement 转换为 String

json - 使用 Typescript 进行持久化

java - "org.springframework.beans.factory.UnsatisfiedDependencyException"的原因是什么?

java - Spring Cloud 流卡夫卡 : Duplicate @StreamListener mapping for 'input'

java - 用于 Java Swing 应用程序的 UI 自动化工具,具有记录和回放以及屏幕捕获功能

java - 使用 Junit 5 的 RestController unsit 测试中没有名为 'entityManagerFactory' 的 bean

java - moxy jaxb @XmlID 和继承

angular - NativeScript 与 Flutter

angular - VSCode tasks.json for ng build --watch

java - 从外部覆盖 Spring 项目的配置