0

I am sending reactive form data through post request to java restful web api but it shows me CORS error While same is working fine in GET request. I already set the CORS header in response of rest api.

Angular Service Code :

 private headers = new Headers({ 'Content-Type': 'application/json'});
    baseURL='http://127.0.0.1:8080/userInformation/rest/UserService';
    addData(formdata: any){
        var body = JSON.stringify(formdata);
           return this.http.post(this.baseURL+'/adduser',body)
                            .subscribe(
                           res => {
                            console.log(res);
                         },
                      err => {
                        console.log('Error occured');
                      }
          );


  }

JAVA Rest API CODE :

       @POST
       @Produces(MediaType.APPLICATION_JSON)
       @Consumes(MediaType.APPLICATION_JSON)
       @Path("/adduser")
       public Response createUser(String val){  
           Gson gson = new Gson();
           User user = gson.fromJson(val, User.class);
           userDao.insertUser(user);
           String result="SUCCESS";
           return Response.ok().entity(result)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD")
                    .build();
       }

Header Description : enter image description here I think when we are sending the data to rest api we need to set the CORS origin header to our angular code. How can I do this?

4

3 回答 3

2

您可以通过在 Controller 类声明上使用注释来解决它。

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping({ "/controller" })
public class Controller {
}
于 2020-01-31T12:56:46.437 回答
0

我们需要为传入请求添加过滤器,如下所示:

创建一个过滤器 CrossOrigin,如下所示:

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

public class CrossOrigin implements ContainerResponseFilter {

     @Override
        public ContainerResponse filter(ContainerRequest creq, ContainerResponse cresp) {

            cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
            cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
            cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
            cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

            return cresp;
        }
}

然后在 web.xml 中注册它:

    <servlet>
        <servlet-name>Jersey RESTful Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>jersey.config.server.provider.packages</param-name>
          <param-value>com.newgen.ap2</param-value>
        </init-param>
        <init-param>
        <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
        <param-value>com.newgen.ap2.CrossOrigin</param-value>
     </init-param>

  </servlet>
于 2018-01-20T12:23:00.553 回答
0

您可以通过使用代理配置运行 Angular 来完成此操作,而无需更改后端。更多细节在这里

简而言之

  1. 将您baseUrl的端口更改为 4200(或您的 Angular 应用程序运行的任何一个):

    baseURL = 'http://127.0.0.1:4200/userInformation/rest/UserService';
    
  2. 在 Angular 项目的根目录中创建一个proxy.conf.json文件,内容如下:

    {
      "/userInformation": {
        "target": "http://127.0.0.1:8080",
        "secure": false
      }
    }
    
  3. 运行 Angular 应用程序ng serve --proxy-config proxy.conf.json

此时您的应用程序在端口 4200 上运行,当您尝试访问包含 的端点时/userInformation,它会劫持 URL 并将其发送到您在代理配置中设置的目标以及路径的其余部分,因此http://127.0.0.1 :8080/userInformation/rest/UserService/addUser。顺便说一句,如果你的端点不在你的后端,浏览器开发控制台会抱怨端口 4200 上的那个端点,但调用确实是 8080。

于 2018-01-20T00:00:14.743 回答