首页 > 解决方案 > 跨域请求被阻止:同源策略不允许读取远程资源

问题描述

我刚刚开始研究 Angular(Angular CLI:9.1.12,Node:12.16.2)。我正在学习角度的基础知识。

我有一个 Django REST API 在本地运行 -

http://127.0.0.1:8000/view/websyellow/

现在我想从角度进行正常的邮政服务。服务在 GET 操作上运行良好,但对于 POST 它给出了一个错误 -

在此处输入图像描述

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/view/websyellow/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).


Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/view/websyellow/. (Reason: CORS request did not succeed).

我正在使用 Mozilla。

服务代码 -

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ScrapeService {

  constructor( private httpclient : HttpClient ) { }

  checkpostservice(postresource){
    return this.httpclient.post('http://127.0.0.1:8000/view/check', postresource)
  };

  realpostservice(postresource){
    return this.httpclient.post('http://127.0.0.1:8000/view/websyellow/', postresource)
  };
}

组件 ts 文件 -

import { Component, OnInit } from '@angular/core';
import { ScrapeService } from '../scrape.eservice';
import { Observable } from 'rxjs';

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

  constructor( public scrapeService : ScrapSeervice ) { }

  ngOnInit(): void {
  }

  postfuncflag = false;
  datalist : any;

  webscrapefunpost(){
    const postdata = {"looking_for":"plumber", "place":"south sc" };
    this.scrapSeervice.realpostservice(postdata).subscribe( data =>{
      this.postfuncflag = true;
      this.datalist = data;
      console.log("here we hit mock POST func for scrape service");
      console.log(this.datalist);
    })
  }
}

组件 HTML 文件 -

<p>webscrape works!</p>

<button (click) = "webscrapefunpost()" >Click here for Web Scraping data.</button>

<br>
<br>
<div *ngIf = "postfuncflag" >
    <table class = "table" >
        <th>Id</th>
        <th>Name</th>
        <th>Phone No.</th>
        <th>Website</th>
        <tr *ngFor = "let ele of datalist" >
            <td>{{ ele.id }}</td>
            <td>{{ ele.name }}</td>
            <td>{{ ele.phone }}</td>
            <td>{{ ele.Website }}</td>
        </tr>
    </table>
</div>

但是,如果我使用任何服务器链接,它就可以像任何第三方 REST API 一样正常工作。

我怎么解决这个问题。

标签: angularmultidimensional-arrayservicedjango-rest-frameworkcors

解决方案


这是一项安全功能。

您要么使用Angular Proxy,要么将CORS 标头添加到 API。


推荐阅读