我想在我的 http 标头中发送身份验证令牌以连接到我用 java 编写的后端 rest-api。
从角度来看,代码就像(service.ts):
getDataFromBackend() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
//this.getAuthToken() retrives auth token from cookies
headers.append("authToken",this.getAuthToken());
return this._http.get('url', {headers:headers})
.map(this.parseData)
}
private parseData(res: Response) {
return res.json || [];
}
从后端:
@Path("/path")
@GET
public Response getData() {
//retrive data from db and call required service to process
return Response.ok(result)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.status(Status.OK).build();
}
现在,当以角度调用服务方法时,出现错误。
请求标头详细信息:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:authtoken,content-type
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8085
Origin:http://localhost:3000
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
回应是:
Authentication failed - Token absent
控制台错误:
OPTIONS http://localhost:8085/*url* 401 (Unauthorized)
Failed to load http://localhost:8085/*url*: 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:3000' is therefore not allowed access. The response had HTTP status code 401.
我无法弄清楚如何解决这个问题?