【问题标题】:Cors Error once deployed Angular and SpringBoot App in Heroku在 Heroku 中部署 Angular 和 Spring Boot 应用程序时出现 Cors 错误
【发布时间】:2021-01-27 16:32:15
【问题描述】:

由于 cors 的原因,我在这个应用程序上经历了非常艰难的时期。 在本地工作完美,但一旦部署错误


Access to XMLHttpRequest at 'https://portafolioback.herokuapp.com/portafolio/version1/post/all' from origin 'https://frontportafolio.herokuapp.com' 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.

应用程序的两个部分(前端(Angular)和后端(Spring-Boot))已经部署在 heroku 中,我的 控制器前端的配置是这样的

import { EventEmitter, Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

const mongoUrl ='https://portafolioback.herokuapp.com/portafolio/version1/';

const myMail = 'https://mailthis.to/cubancoder@gmail.com';
let headersReq = new HttpHeaders({
  'Content-Type': 'application/json; charset=utf-8',
});

@Injectable({
  providedIn: 'root',
})
export class PostServicesService {
 
  constructor(private http: HttpClient) {}
  ...some code.....
  getAllPosts() {
    return this.http.get<any>(`${mongoUrl}post/all`, { headers: headersReq });
  }
}

在我的背后,控制器看起来像这样:

@CrossOrigin(origins = "https://frontportafolio.herokuapp.com", maxAge = 3600)
@RestController
@RequestMapping("portafolio/version1")
public class PostController {

    @Autowired
    private PostRepository postRepository;

    @GetMapping("/post/all")
    public List<Post> getAllPost(){
        return postRepository.findAllComments();
    }
}

然后由于CrossOrigin的这个配置也没有用,我在我的应用程序文件中添加了一个这样的cors全局配置:

package com.portafolio.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

@Configuration
@EnableWebMvc
 class WebConfig implements Filter,WebMvcConfigurer {



    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        System.out.println("WebConfig; "+request.getRequestURI());
        response.setHeader("Access-Control-Allow-Origin", "https://frontportafolio.herokuapp.com");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        response.addHeader("Access-Control-Expose-Headers", "responseType");
        response.addHeader("Access-Control-Expose-Headers", "observe");
        System.out.println("Request Method: "+request.getMethod());
        if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
            try {
                chain.doFilter(req, res);
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Pre-flight");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
                    "USERID"+"ROLE"+
                    "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
            response.setStatus(HttpServletResponse.SC_OK);
        }

    }

}

但仍然有同样的错误:

Access to XMLHttpRequest at 'https://portafolioback.herokuapp.com/portafolio/version1/post/all' from origin 'https://frontportafolio.herokuapp.com' 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.

请...任何有关这种情况的帮助将是惊人的!! 提前谢谢!!!

【问题讨论】:

    标签: java angular spring-boot xmlhttprequest cors


    【解决方案1】:

    尝试允许凭据

    我在处理它时遇到了同样的问题。Heroku 只会从你的依赖项中安装包 我需要的是在我的 devDependencies 中,所以一旦我作为依赖项重新安装它就可以了!

    将此代码添加到 serve.js 喜欢:

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", '*');
        res.header("Access-Control-Allow-Credentials", true);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
        next();
    });
    

    尝试在服务文件中添加Access-Control-Allow-Methods

    import { EventEmitter, Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { BehaviorSubject } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    const mongoUrl 
      ='https://portafolioback.herokuapp.com/portafolio/version1/';
        
    
    const myMail = 'https://mailthis.to/cubancoder@gmail.com';
    let headersReq = new HttpHeaders({
      'Content-Type': 'application/json; charset=utf-8',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Allow-Methods': 'GET',
      'Access-Control-Allow-Origin': '*'
    });
    
    @Injectable({
      providedIn: 'root',
    })
    export class PostServicesService {
     
      constructor(private http: HttpClient) {}
      ...some code.....
      getAllPosts() {
        return this.http.get<any>(`${mongoUrl}post/all`, { headers: headersReq });
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 2020-12-01
    • 2020-11-21
    • 1970-01-01
    • 2020-03-05
    • 2018-06-28
    • 2021-03-25
    • 2023-02-24
    相关资源
    最近更新 更多