简体   繁体   English

无法从角度6 httpclient向Java servlet发送请求

[英]unable to send request to java servlet from angular 6 httpclient

how to connect from Angular to java Servlet? 如何从Angular连接到Java Servlet? here is my angular service code 这是我的角度服务代码

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable({ providedIn: "root" })
export class UploadService {
  url: string;
  constructor(private http: HttpClient) {
    this.url = "http://localhost:8081/ServletSample/";
  }

  uploadFile(data): Observable<any> {
    return this.http.post(this.url, data);
  }

  sendData(data): Observable<any> {
    return this.http.post(this.url + "DataServlet", data);
  }
}

below is Authservice 下面是Authservice

import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor } from "@angular/common/http";
import { HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      headers: req.headers.set("X-CustomAuthHeader", "aaaa")
    });
    console.log("req", req);
    console.log("new headers", clonedRequest.headers.keys());

    return next.handle(clonedRequest);
  }
}

java servlet is running in below port java servlet在以下端口中运行

http://localhost:8081/ServletSample/DataServlet

below is java servlet code 以下是Java Servlet代码

package com.test.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DataServlet extends HttpServlet{

      /**
     * 
     */
    private static final long serialVersionUID = 548987777;

    public DataServlet() {
            super();
            System.out.println("DataServlet constructor called");
        }

        /**
         * @see Servlet#init(ServletConfig)
         */
        public void init(ServletConfig config) throws ServletException {
            System.out.println("DataServlet \"Init\" method called"+ config.toString());
        }

        /**
         * @see Servlet#destroy()
         */
        public void destroy() {
            System.out.println("DataServlet \"Destroy\" method called");
        }


        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
        {
            System.out.println("DataServlet doGet method called"+ request);
            doPost(request, response);

        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("DataServlet doPost method called");
        }

}

but when i am sending request getting below error in browser console 但是当我发送请求时浏览器控制台中出现以下错误

Access to XMLHttpRequest at ' http://localhost:8081/ServletSample/DataServlet ' from origin ' http://localhost:4201 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 从源' http:// localhost:4201 '对' http:// localhost:8081 / ServletSample / DataServlet '处的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'访问-Control-Allow-Origin'标头出现在请求的资源上。

Judging from the error that you're getting, you'll have to enable CORS on the servlet to allow accepting calls from other origins. 根据收到的错误判断,您必须在Servlet上启用CORS才能接受来自其他来源的调用。

Just create a private method and call it from the methods where you're sending the actual response. 只需创建一个private方法,然后从发送实际响应的方法中调用它即可。 You can set the headers in this method. 您可以在此方法中设置headers Something like this: 像这样:

private void setAccessControlHeaders(HttpServletResponse resp) {
  resp.setHeader("Access-Control-Allow-Origin", "http://localhost:9000");
  resp.setHeader("Access-Control-Allow-Methods", "GET");
}

Source: Servlet - Cross-origin resource sharing (CORS) 来源: Servlet-跨域资源共享(CORS)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM