使用Access-Control-Allow-Origin访问REST失败的Angular 6
所以我试图使用来自’@ angular / common / http’的http:HttpClient将来自REST源的数据加载到我的Angular 6应用程序中.使用ng serve –open在浏览器中调用应用程序虽然不起作用.我认为CORS是这里的问题.我想我要么必须使用Access-Control-Allow-Origin等设置服务器或客户端头,但我已经尝试了多种方法,但没有成功地使这个简单的REST调用工作.以下是我编码的内容.
在浏览器中调用Angular应用程序会响应以下错误: Failed to load http://localhost:8080/mysite-backend/rest/report/single/d83badf3: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 在Chrome浏览器中调用相同的URL(http:// localhost:8080 / mysite-backend / rest / report / single / d83badf3)可以很好地工作: {"id":"d83badf3","language":"en","categoryId":"a5","title":"Simcity","created":1527723183880,"modified":1527723183880} 在Angular 6中,我使用以下生成的服务类,使用ng生成服务导览.在其中我创建了方法getTour(id:string),它不仅仅是在URL上调用REST,而是将检索到的JSON字符串作为Tour对象返回: import { Injectable } from '@angular/core'; import { HttpHeaders,HttpClient } from '@angular/common/http'; import { Observable,of } from 'rxjs'; import { Tour } from './tour'; import { catchError,tap } from 'rxjs/operators'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable({ providedIn: 'root' }) export class TourService { // URL to the web api. private tourUrl = 'http://localhost:8080/mysite-backend/rest/report'; constructor( private http: HttpClient ) { } /** * * @param id: string GET tour report by id. Will 404 if id not found. */ getTour(id: string): Observable<Tour> { httpOptions.headers.append('Access-Control-Allow-Origin','http://localhost:8080'); httpOptions.headers.append('Access-Control-Allow-Methods','GET,POST,OPTIONS,PUT,PATCH,DELETE'); httpOptions.headers.append('Access-Control-Allow-Headers','X-Requested-With,content-type'); httpOptions.headers.append('Access-Control-Allow-Credentials','true'); const url = `${this.tourUrl}/single/${id}`; console.log("XXX URL GET " + url) return this.http.get<Tour>(url,httpOptions).pipe( tap(_ => this.log(`fetched tour id=${id}`)),catchError(this.handleError<Tour>(`getHero id=${id}`)) ); } private handleError<T> (operation = 'operation',result?: T) { return (error,any): Observable<T> => { console.error(error); this.log(`${operation} failed: ${error.message}`); return of(result as T); }; } private log(message: string) { console.log("Log message: " + message); } } 这是Tour对象: export class Tour { id: string; language: string; categoryId: string; created: Date; modified: Date; title: string; content: string; } 我还将’@ angular / common / http’中的HttpClientModule添加到了app.module.ts中的进口数组和providers数组中. RESTful WebService是用Java构建的.这里我有getReport(@PathParam(“reportId”)String reportId)方法,它获取一个Report对象并在Reponse中返回它: import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Describes the RESTful access for reports. */ @Path("/report") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ReportResource { @Inject private Logger logger; @GET @Path("/single/{reportId}") public Response getReport(@PathParam("reportId") String reportId) { //return Mock.getReport(reportId); return Response.ok() // 200 .entity(Mock.getReport(reportId)) .header("Access-Control-Allow-Origin","*") .header("Access-Control-Allow-Methods","GET,DELETE,PUT") .allow("OPTIONS").build(); } ... } 如何从Angular 6客户端成功调用Java RESTful WebService,我该怎么做? 解决方法
问题与角度本身无关,而与您正在使用的Web服务器有关.
在发出实际请求之前,角度http客户端请求始终具有带有类型选项的预检请求. 您可能需要向此行添加OPTIONS请求方法 .header("Access-Control-Allow-Methods",PUT") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |