简体   繁体   English

在 Angular 4 中将数据发送到 JAVA post REST API 时出现 CORS 错误

[英]Getting CORS error when sending data to JAVA post REST API in Angular 4

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.我正在通过 post 请求向 java restful web api 发送反应式表单数据,但它显示我的 CORS 错误,而在 GET 请求中同样工作正常。 I already set the CORS header in response of rest api.我已经设置了 CORS 标头以响应 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 : JAVA 休息 API 代码:

       @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. Header Description :在此处输入图像描述我认为当我们将数据发送到 rest api 时,我们需要将 CORS 源头设置为我们的角度代码。 How can I do this?我该怎么做?

You can resolve it by using annotation on the Controller class declaration.您可以通过在 Controller 类声明上使用注释来解决它。

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping({ "/controller" })
public class Controller {
}

You can do this without changing the backend by running Angular with a proxy configuration.通过使用代理配置运行 Angular,您可以在不更改后端的情况下执行此操作。 More details here .更多细节在这里

In a nutshell :简而言之

  1. Change your baseUrl 's port to 4200 (or whichever your Angular app runs on):baseUrl的端口更改为 4200(或运行 Angular 应用程序的任何端口):

     baseURL = 'http://127.0.0.1:4200/userInformation/rest/UserService';
  2. Create a proxy.conf.json file in the root of your Angular project with the content:在 Angular 项目的根目录中创建一个proxy.conf.json文件,内容如下:

     { "/userInformation": { "target": "http://127.0.0.1:8080", "secure": false } }
  3. Run the Angular app with ng serve --proxy-config proxy.conf.json使用ng serve --proxy-config proxy.conf.json运行 Angular 应用

At this point your app runs on port 4200 and when you try to hit an endpoint containing /userInformation , it hijacks the URL and sends it to the target you set in your proxy configuration plus the rest of the path, so http://127.0.0.1:8080/userInformation/rest/UserService/addUser .此时,您的应用程序在端口 4200 上运行,当您尝试访问包含/userInformation的端点时,它会劫持 URL 并将其发送到您在代理配置中设置的目标以及路径的其余部分,因此http://127.0 .0.1:8080/userInformation/rest/UserService/addUser By the way, if your endpoint is not up in your backend, the browser dev console will complain about that endpoint on port 4200, but the call really went to 8080.顺便说一下,如果您的端点不在后端,浏览器开发控制台会在端口 4200 上抱怨该端点,但调用确实转到了 8080。

We need to add filter for incoming request as below:我们需要为传入请求添加过滤器,如下所示:

Create a filter CrossOrigin as below :创建一个过滤器 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;
        }
}

And then register it in web.xml :然后在 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java REST API 发送 GET 请求时出错,但在 POST 上工作 - Java REST API Getting Error when sending GET Request, but works on POST 将带有JSON数据的POST请求从HTML发送到Java Rest Web服务时出现HTTP错误415 - HTTP Error 415 when sending POST request with JSON data from HTML to Java Rest web service 将POST请求发送到REST API时出现415错误 - 415 error when sending POST request to REST API Sending POST request with POSTMAN to Java REST API and getting null values in the xml response - Sending POST request with POSTMAN to Java REST API and getting null values in the xml response 具有大数据量的呼叫发布休息API时引发错误 - Error thrown when call post rest api with big data size 将multipartfile发送到REST API时出现Spring错误 - Spring error when sending multipartfile to REST api 使用Java Jersey API对REST API的发布请求获取错误405 - Getting Error 405 for post request to REST api using Java Jersey api 使用Java从Playframework中的控制器向REST API发送发布请求 - Sending a post request to REST API from controller in Playframework with Java Java Rest发送数据 - Java Rest sending data 从Angular Js(Java Web)调用API时发生CORS错误 - CORS error while API calling from Angular Js (Java web)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM