【问题标题】:CORS specifics in Angular 8Angular 8 中的 CORS 细节
【发布时间】:2020-07-11 00:06:27
【问题描述】:

关于我的以下两个版本的代码,我不明白 Angular 的行为有何不同。

v1:无缝运行

onSubmit() {
// selects all marked as checked students from from
const selectedStudents = this.studentsFormGroup.value.students
.map((checked: boolean, index: number) => checked ?
  this.listOfStudents[index].id : null)
.filter((value: number) => value !== null);

// create Student in remote_db
selectedStudents.forEach((id: number) => {
  this.studentService.createStudentById(id);
  console.warn('student created: ' + id);
});

v2:给我一个

在“http://localhost:8888/api/v3/students”访问 XMLHttpRequest 来自原点“http://localhost:4200”已被 CORS 策略阻止: 请求中不存在“Access-Control-Allow-Origin”标头 资源。

onSubmit() {
// selects all marked as checked students from from
const selectedStudents = this.studentsFormGroup.value.students
.map((checked: boolean, index: number) => checked ? [
  this.listOfStudents[index].id,
  this.listOfStudents[index].name,
  this.listOfStudents[index].surname] : null)
.filter((value: any) => value !== null);

// create Student in remote_db
selectedStudents.forEach((student: any) => {
  this.studentService.createStudentById(student.id);
  console.warn('student created: ' + student);
});

谁能解释我没有得到什么?我需要第二个版本,因为在未来的代码中,我将需要数组的附加信息。任何建议如何做到这一点。

  • 我按照建议添加了 proxy.conf.json
  • 我验证了我的 api 后端 (slim 4) - 适用于其他服务就好...

提前致谢。

【问题讨论】:

  • 您是否能够验证this.studentService.createStudentById 是否已在两种情况下使用相同的值调用?快速浏览一下让我相信,对于 v2,可以使用“未定义”进行调用。并且间接地您调用了错误的 URL,由于缺少 CORS 标头,您的浏览器意外地拒绝了该 URL。
  • 谢谢。这让我走上了正轨。我确实得到了一个“未定义”。 this.studentService.createStudentById(student[0]) 效果很好。如果您关心,请发表您的评论作为答案,我会检查它:)
  • 如果您收到 CORS 错误,响应的 HTTP 状态代码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?
  • 我得到了 500。请查看答案下方的评论以获取详细信息

标签: angular typescript rest api


【解决方案1】:

虽然

checked ?
  this.listOfStudents[index].id : null

确保“id”是“truthy”或“null”(因此随后被过滤掉)v2 不进行此类检查,因此可能会出现“未定义”ID,从而导致错误的 URL 被定位。

【讨论】:

  • 我在 v2 中的代码生成了一个简单的数组,不能使用命名键作为目标。因此,正如您在评论中所说,它给了我一个未定义的反馈,因此是服务器 500 反馈。我现在会处理我的 api 以便更好地处理错误 :) 感谢您的时间
猜你喜欢
  • 1970-01-01
  • 2020-05-06
  • 2020-02-21
  • 2020-01-23
  • 2020-05-23
  • 1970-01-01
  • 2015-08-18
  • 2020-05-29
  • 1970-01-01
相关资源
最近更新 更多