我刚刚开始使用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 ScrapService {
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 { ScrapService } from '../scrap.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-webscrap',
templateUrl: './webscrap.component.html',
styleUrls: ['./webscrap.component.css']
})
export class WebscrapComponent implements OnInit {
constructor( public scrapService : ScrapService ) { }
ngOnInit(): void {
}
postfuncflag = false;
datalist : any;
webscrapfunpost(){
const postdata = {"looking_for":"plumber", "place":"south sc" };
this.scrapService.realpostservice(postdata).subscribe( data =>{
this.postfuncflag = true;
this.datalist = data;
console.log("here we hit mock POST func for scrap service");
console.log(this.datalist);
})
}
}
组件HTML文件-
<p>webscrap works!</p>
<button (click) = "webscrapfunpost()" >Click here for Web Scrapping 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一样正常工作。
我该如何解决这个问题。