0

我在本教程中完全发现了 angular 6,我会尝试使用 angular-cli 前端询问 djangorestframework 后端 api。

看起来我的前端只向后面发送一个 OPTIONS 请求(根据 Mozilla 的网络选项卡)。我尝试使用邮递员工具访问数据,并从后端得到正确的响应。

我在控制台选项卡上收到此错误:ERROR Object { headers: Object, status: 0, statusText: "Unknown Error", url: null, ok: false, name: "HttpErrorResponse", message: "Http failure response for (unknown …", error: error }

在你问我设置"Access-Control-Allow-Origin": "*"删除 CORS 错误之前,我仍然无法访问我的后端数据。

这是我的前端代码:domain-analysis.service.ts

import { Injectable } from '@angular/core';
import { DomainAnalyse} from './domain-analyse';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

import {ANALYSES}   from './mock-analyse'
import { Domain } from 'domain';

@Injectable({
  providedIn: 'root'
})
export class DomainAnalyseService {
  private urlBase = 'http://localhost:8000/api/v1.0/analyse/' 
  public domainList: DomainAnalyse[]
  getDomainSpecificAnalyse (domain, analyse) {
    const body = {'domain': domain}
    const urlCalled = this.urlBase+analyse
    return this.http.post(urlCalled, body);
  }
  constructor(private http: HttpClient) { }
}

域分析.component.ts

import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';

import { DomainAnalyseService } from '../domain-analyse.service';
import { DomainAnalyse }        from '../domain-analyse'

@Component({
  selector: 'app-domain-analyse',
  templateUrl: './domain-analyse.component.html',
  styleUrls: ['./domain-analyse.component.css']
})
export class DomainAnalyseComponent implements OnInit {

  public domain: DomainAnalyse

  constructor(
    private activatedRoute: ActivatedRoute,
    private domainAnalyseService: DomainAnalyseService
  ) { }

  analyseDomain (domain, analyse): Object {
      return this.domainAnalyseService.getDomainSpecificAnalyse(domain, analyse).subscribe(
        (analyse: DomainAnalyse) => this.domain = {...analyse}
      );
  }

  ngOnInit() {
    // subscribe to router event
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.analyseDomain(params.domain, params.analyse)
    });
  }

}

领域分析.ts

export class DomainAnalyse{
    constructor(
        public name: string,
        public analyse: string,
        public url: string,
        public date: string,
        public grading: Grading,
    ){}
}

export class Grading{
    constructor(
        public score: number,
        public grade: string,
        public color: string,
        public analyse_type: string,
        public displayable_element: Displayable[],
    ){}
}

export class Displayable{
    constructor(
        public score: number,
        public symbole: string,
        public color: string
    ){}
}

如果缺少某些内容,我可以将其添加到帖子中。

感谢您的帮助。

4

1 回答 1

0

你能提供网络日志的.har文件吗?(使用chrome)右键单击任何网络请求,然后说“另存为带有内容的har”,然后将其上传到我们可以访问的地方。

于 2018-06-04T16:03:57.340 回答