如何从Angular连接到Java Servlet? 这是我的角度服务代码
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);
}
}
以下是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在端口
下运行http://localhost:8081/ServletSample/DataServlet
下面是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");
}
}
但是当我发送请求时,浏览器控制台出现以下错误
从原点“ http://localhost:8081/ServletSample/DataServlet”到“ http://localhost:4201”的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否“访问控制” -Allow-Origin'标头出现在请求的资源上。
答案 0 :(得分:1)
从收到的错误来看,必须在servlet上启用CORS才能接受来自其他来源的调用。
只需创建一个private
方法,然后从发送实际响应的方法中调用它即可。您可以使用此方法设置headers
。像这样:
private void setAccessControlHeaders(HttpServletResponse resp) {
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:9000");
resp.setHeader("Access-Control-Allow-Methods", "GET");
}