我选择了之前的工作应用程序(Angular2)并发现它现在无法正常工作(Angular4)。
使用了模块(可能无关紧要):
import { HttpModule, JsonpModule } from '@angular/http';
现在使用的模块:
import { HttpClientModule} from '@angular/common/http';
尝试从后端(Node.js,Express和MongoDB)获取记录列表,如下所示。
listResource(resType: string, parameters: string[]) {
console.log("***listResource");
let headers = new HttpHeaders().set("X-CustomHeader", "custom header value");
headers.append('Content-Type', 'application/fhir+json');
headers.append("'Access-Control-Allow-Origin", "*");
headers.append("Accept", "application/fhir+json");
headers.append("USER_KEY", "QIF83Fjoe4sYxdQsah3h"); //TOUCHSTONE KEY
let urlString = this.baseUrl + resType + "/list"; // + queryString;
console.log("List resource URL string: [" + urlString + "]");
return (this.httpClient.get(urlString, { headers })
.map((res: Response) => res.json()))
.catch((error: any) => Observable.throw(error.json().error || 'Server error from Observable http.get call')); //...errors if any
}
当我的组件被加载时,上面的listResource将被调用如下。
ngOnInit() {
//Get the initial 25 latest patient
//this.progressBar = true;
this.currentPage = 0;
this.patientList = [];
this.globalSvc.gPatient = [];
console.log("***OnInit");
this.restSvc.listResource("Patient", ["identifier=*", "family=*", "given=*"]).subscribe(
data => {
console.log("Response data: " + JSON.stringify(data));
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
});
}
以下是Chrome控制台的输出。当然,我没有得到任何好的回应。在我看来,Chrome浏览器发送CORS选项,服务器响应正确,然后浏览器不发送实际的GET。
如果我直接从PostMan发送没有CORS的REST API请求,我会从服务器获得预期的良好响应。因此,在我看来服务器还可以。
问题:
答案 0 :(得分:1)
headers.append()不会改变标题,它会返回一个新的标题(因为标题是不可变的)。
所以,而不是
let headers = new HttpHeaders().set("X-CustomHeader", "custom header value");
headers.append('Content-Type', 'application/fhir+json');
headers.append("'Access-Control-Allow-Origin", "*");
headers.append("Accept", "application/fhir+json");
headers.append("USER_KEY", "QIF83Fjoe4sYxdQsah3h"); //TOUCHSTONE KEY
你需要做类似的事情:
let headers = new HttpHeaders().set("X-CustomHeader", "custom header value")
.append('Content-Type', 'application/fhir+json')
.append("'Access-Control-Allow-Origin", "*")
.append("Accept", "application/fhir+json")
.append("USER_KEY", "QIF83Fjoe4sYxdQsah3h");
哦,那应该是const headers =
,而不是let headers =