Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs ';http://localhost:4200' 已被CORS策略阻止:否';访问控制允许原点';请求的资源上存在标头_Angularjs_Spring Boot - Fatal编程技术网

Angularjs ';http://localhost:4200' 已被CORS策略阻止:否';访问控制允许原点';请求的资源上存在标头

Angularjs ';http://localhost:4200' 已被CORS策略阻止:否';访问控制允许原点';请求的资源上存在标头,angularjs,spring-boot,Angularjs,Spring Boot,我正在尝试使用spring boot和angular更新数据,但每当我尝试更新数据时,我得到的错误“”已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头 这是我的弹簧控制器和角度服务 我尝试了stackoverflow的其他解决方案,但不起作用 请告诉我我做错了什么 InfoController.java @RestController @RequestMapping("/student") public class InfoControlle

我正在尝试使用spring boot和angular更新数据,但每当我尝试更新数据时,我得到的错误“”已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头

这是我的弹簧控制器和角度服务

我尝试了stackoverflow的其他解决方案,但不起作用 请告诉我我做错了什么

InfoController.java

@RestController
@RequestMapping("/student")
public class InfoController {

@Autowired
private InfoDAO infoDAO;

@CrossOrigin(origins = "http://localhost:4200")

@PutMapping("/infos/{id}")
public List<Info> updateStudent(@RequestBody Info info, @PathVariable int id) {

    List<Info> information = infoDAO.getbyID(id);

    System.out.println("this is id");

    info.setId(id);

    infoDAO.update(info);

    // info1.update(info1);

    return information;
}

  } 
List<Info> getbyID(int id);
boolean update(Info info);
public class InfoDAOImpl implements InfoDAO {

@PersistenceContext
@Autowired
private EntityManager em;

@Override
public List<Info> getbyID(int id) {
    String query = "FROM Info WHERE id = :id";
    return em
                .createQuery(query,Info.class)
                .setParameter("id",id)  
                .getResultList();
 }

public boolean update(Info info) {
    try {           
        em
                    .merge(info);
        return true;
    }
    catch(Exception ex) {       
        return false;
    }                   
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired DataSource dataSource;

@Override
protected void configure(HttpSecurity http) throws Exception { 
     http.
     cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
    .and().csrf().disable()
            .authorizeRequests()                                                                
            .antMatchers("/**").permitAll()
            .antMatchers("/login").hasRole("ADMIN")                                      
            .antMatchers("/Signup").hasRole("USER")
            .and()
            .exceptionHandling()
            .accessDeniedPage("/access-denied")
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailService));
}

@Bean   
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Origin","Authorization", "Cache-Control", "Content-Type", "xsrfheadername","xsrfcookiename"
    ,"X-Requested-With","XSRF-TOKEN","Accept", "x-xsrf-token","withcredentials","x-csrftoken"));
    configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration); 
    return source; 
}
Web.service.ts

export class WebService {

constructor(private httpClient: HttpClient) { }

serverUrl = 'http://localhost:8083/student';

editPlan(data: Student, id:any): Observable<any> {
    const url = `/infos/${id}`;
    return this.httpClient.put(this.serverUrl + url, data);
}

getWebPlanInfo(): Observable<any> {
    const url = '/plan/info';
    return this.httpClient.get(this.serverUrl + url);
}

}
导出类Web服务{
构造函数(私有httpClient:httpClient){}
服务器URL=http://localhost:8083/student';
editPlan(数据:学生,id:any):可观察{
常量url=`/infos/${id}`;
返回this.httpClient.put(this.serverUrl+url,数据);
}
getWebPlanInfo():可观察{
常量url='/plan/info';
返回this.httpClient.get(this.serverUrl+url);
}
}

在spring安全配置中,请使用以下命令:,因此,您正在创建的
corscoConfiguration
bean将由spring自动执行,而不是您在http bean本身中提供的配置。在您的配置中,您使用新的操作符手动创建实例,而不是让spring自动连接实例
corscoConfiguration
bean,您在下面提供。所以,试试看:

@Override
protected void configure(HttpSecurity http) throws Exception { 
     http.
     cors().and().csrf().disable()
            .authorizeRequests()                                                                
            .antMatchers("/**").permitAll()
            .antMatchers("/login").hasRole("ADMIN")                                      
            .antMatchers("/Signup").hasRole("USER")
            .and()
            .exceptionHandling()
            .accessDeniedPage("/access-denied")
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailService));
}


@Bean   
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
    configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration); 
    return source; 
}

理论上,如果您设置正确,spring security应该自动向您的响应添加响应头,如
Access Control Allow Origin
。官方

此问题与以下行有关
cors().configurationSource(请求->新的cors配置().applyPermitDefaultValues())

如果您删除这条线,它将工作

但是怎么做呢?这是因为您的
@Bean
方法
corscoconfigurationsource
将在运行时由spring容器加载,它将为此创建Bean

通过添加此行
cors().configurationSource(请求->新建corscoConfiguration().applyPermitDefaultValues())
它将覆盖Bean
corscoconfigurationSource

默认情况下,
corscoConfiguration
类中的此方法
applyPermitDefaultValues()
将允许
GET
POST
HEAD
请求方法。因此,您的
PUT/DELETE
方法不起作用


参考:

删除此行
cors().configurationSource(请求->新建corscoConfiguration().applyPermitDefaultValues())
并检查。@gnana jeyam95再次遇到同样的问题,插入操作正常,但编辑和删除被cors策略阻止。你的解决方案终于对我起作用了。谢谢,酷。你了解这个问题吗?不,我不明白为什么一个请求有效而另一个无效。@gnana jeyam95你应该将它作为答案发布,因为我在任何地方都找不到解决问题的方法。