CORS Angular 8 它给了我 [英] CORS Angular 8 it gives me

查看:23
本文介绍了CORS Angular 8 它给了我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中存在 CORS 问题.我从 Angular 8 开始:

I have a CORS problem in my project. From Angular 8 I do:

 httpOptions = { 
      headers: new HttpHeaders({
        'Content-Type':'application/json',
        'Authorization':'Basic bm92Z*********************'
      })
    };

而且我确实以这种方式进行操作:

and I do get operation in this way:

public getStudents() : Observable<IStudent[]>{
  return this.http.get<IStudent[]>(this.writeUrl, this.httpOptions)...// this.writeUrl is the request  url
}

在我使用 java 的服务器中,我这样做:

In my server with java I do:

public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {

    responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Headers",
    "origin, content-type, accept, authorization");
    responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
    responseContext.getHeaders().add("Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, OPTIONS, HEAD");

    }

它给了我 CORS,我不知道为什么,有人可以帮助我吗?

it gives me CORS and I don't know why, anyone can help me?

推荐答案

Angular 服务器运行在 http://localhost:4200/ 和 Spring Boot 服务器运行在 http://localhost:8080/ 上.

Angular server runs on http://localhost:4200/ and spring boot server runs on http://localhost:8080/.

配置一个与 package.json 并行的 proxy.conf.json.proxy.conf.json 应该有

configure a proxy.conf.json parallely to package.json. proxy.conf.json should have

{
  "/api/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

在package.json中配置相同

configure the same in package.json

"scripts" :{"start": "ng serve --proxy-config proxy.conf.json"}

此配置应将您的角度调用代理到 ​​Spring Boot 服务器.让我知道这是否适合您,如果您仍然遇到任何问题,请发布该错误.我们可以从那里检查.

This configuration should proxy your angular calls to spring boot server. Let me know if this works for you, if you still face any issue, post that error. we could check from there.

这篇关于CORS Angular 8 它给了我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆