Micronaut 微服务中的 CORS

CORS in Micronaut Microservice

我正在从事一个小型学校项目,该项目涉及从反应前端访问 java 中使用 Micronaut 构建的微服务。当我最初将我的微服务部署到 Google 云时,我能够从 Postman 远程访问它,但是,当我尝试从 React 前端访问它时,我收到以下错误:

代码:

sendOtp(phoneNumber) {
    fetch(apiRequest, {
      method: 'POST',
      body: JSON.stringify({
        phoneNumber: 'phoneNumber',
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    }).then(response => {
        return response.json()
      }).then(json => {
        this.setState({
          otpResponse:json
        });
      });
  }

错误:

Access to fetch at 'X' from origin 'X' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

我稍微研究了一下 CORS,发现我需要将以下内容添加到我的 application.yml 文件中:

micronaut:
    server:
        cors:
            enabled: true

我还在我的 post 请求中添加了 https://cors-anywhere.herokuapp.com,因为这是我在网上找到的解决方法。

但是,我对此还有几个问题:
1。为什么我可以从 Postman 访问这个微服务,但不能从 React 前端访问?
2。使用 https://cors-anywhere.herokuapp.com 是一种安全的解决方法吗?他们有任何安全问题吗?
3。这个问题是 React/Web 页面独有的吗?如果我想从其他应用程序访问此微服务,是否需要启用 CORS?

谢谢,如有任何帮助,我们将不胜感激!

  1. Why I am able to access this microservice from Postman but not from the React frontend?

因为 CORS 与您的 Postman 请求无关。

  1. Is using https://cors-anywhere.herokuapp.com a safe workaround? Are they any security issues?

通常你不想那样做。您希望配置 CORS 以允许来自前端的请求。

  1. Is this issue exclusive to a React/Web pages? Would I need to enable CORS if I wanted to access this microservice from other applications?

不,它不是 React 独有的。您是否需要启用 CORS 以从其他应用程序访问此服务取决于这些应用程序是什么。如果它们是来自不同来源的浏览器中的 JS 应用程序 运行,是的。如果他们是向您的 API 发出请求的客户端应用程序,则不会。

查看 Allowed Origins 部分 https://docs.micronaut.io/1.2.5/guide/index.html#cors。您将需要配置您的 React 应用程序的来源。

希望对您有所帮助。