即使允许原点,“ cors标头'access-control-allow-origin'丢失”也会拒绝请求

时间:2019-05-24 11:07:29

标签: angular spring-boot

我想从我的角度应用程序向我的服务器发送POST请求(使用spring-boot编写)。该请求被拒绝,并显示消息“缺少cors标头'access-control-allow-origin'”。

我启用了我的角度应用程序“ http://localhost:4200”的原点,就像我为其他RestControllers所做的一样(这是工作)。据我所知,唯一的区别是我在不工作的控制器中处理了POST请求。

控制器

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {

    @Autowired
    private ReqRepository reqRepository;

    @PostMapping("/reqs")
    public Req saveReq (@Valid @RequestBody Req req) {
        return reqRepository.save(req);
    }
}

存储库

@Repository
public interface ReqRepository extends JpaRepository<Req, Long> {
}

角度服务

@Injectable()
export class ReqService {

  private httpOptions = {
    headers: new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    })
};

  constructor(private http: HttpClient) {}

  sendReq(req: Req): Observable<Req> {
    return this.http.post<Req>('http://localhost:8080/reqs', req, this.httpOptions);
  }
}

我认为允许来源就足够了,因此可以提出请求,但请求被阻止了。似乎我缺少启用POST请求的功能。

更新

我进一步测试了控制器,它适用于GET请求。 我只是更改了方法,所以问题似乎出在POST请求中。 在下面的控制器中,使用GET测试端点而不是POST端点

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {

    @Autowired
    private ReqRepository reqRepository;

    @GetMapping("/reqs")
    public Page<Req> testCall (Pageable pageable) {
        System.out.println("Geeting request");
        return reqRepository.findAll(pageable);
    }
}

2 个答案:

答案 0 :(得分:0)

很高兴您的请求现在可以正常工作。请注意'Access-Control-Allow-Origin': '*'是服务器发送的标头。在这里,您尝试将标题从angular发送到服务器,这将不起作用

也请更改@CrossOrigin(origins = "http://localhost:4200")

转到@CrossOrigin(origins = "http://localhost:4200", methods="GET,POST,PUT,DELETE,ORIGIN"),看看是否有效

答案 1 :(得分:0)

问题是我的春季安全配置。 我必须禁用csrf,因为默认情况下它已启用。 我从这篇文章中获得了解决方案:How to Solve 403 Error in Spring Boot Post Request

我的解决方案如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //Override basic security settings so no login page is needed to access the RestEndpoints
    @Override
    protected void configure(HttpSecurity security) throws Exception
    {
        security.httpBasic().disable();
        security.csrf().disable();
    }
}