簡體   English   中英

CORS 阻塞了我的后端服務器,如何解決? 使用 Springboot java 作為后端和 react js 作為我的前端

[英]CORS blocking my backend server, how to fix? Using Springboot java as backend and react js as my front end

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {



  handleSubmit(event) {
    axios.post('http://localhost:3050/login', {
      "username": "username",
      "password": "password"
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
  }

  render() {

      return(

        <form onSubmit={this.handleSubmit}>
          <input type="submit" value="Submit" />
        </form>

      );
  }

}

export default App;

只需檢查后端 json 的用戶名設置為“用戶名”和密碼設置為“密碼”

我的后端是 spring 啟動並使用帶有“用戶名”和“密碼”的結束鏈接 /login 應該會給出一些響應。 因此,除了 CORS 阻止連接之外,此代碼有效,因此它永遠卡在處理中。 我發現的一個解決方案是禁用 chrome 中的所有安全性,它可以工作。 但我正在尋找一個永久的解決方案,而不必禁用 chrome 設置的安全性。 不知道我是通過springboot還是做出反應

嘗試在“@RequestMapping”注釋上方的 spring REST 端點上使用注釋“@CrossOrigin”。

例如:-

    @CrossOrigin
    @RequestMapping(value="/login",method=RequestMethod.POST)

當涉及到請求 POST 時,您可能需要額外的配置,如下所示;

axio({
  method: 'put',
  headers: {
    'Content-Type': 'application/json',
  },
  data: JSON.stringify({
    "username": "username",
    "password": "password"
  }),
});

在你的配置中創建這個bean

 @Bean
public CorsConfigurationSource corsConfigurationSource() {

    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of(
            "http://example.net",
            "http://example.com",
           ));
    configuration.setAllowedMethods(ImmutableList.of("HEAD", "OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(ImmutableList.of("*"));
    configuration.setExposedHeaders(ImmutableList.of("Content-Disposition"));
    configuration.setMaxAge(3600L);

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);

    return source;
}

請在 package 的項目中添加以下文件,其中存在主 spring 引導 class。 這對我來說適用於 Spring 啟動、React 生態系統中的所有 CORS 問題。

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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsWebConfig implements WebMvcConfigurer {

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

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/api/swagger-resources/configuration/ui",
                "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/api/swagger-resources/configuration/security",
                "/swagger-resources/configuration/security");
        registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html**")
                .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
        registry.addResourceHandler("/api/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM