I have just started working on Angular (Angular CLI: 9.1.12, Node: 12.16.2). I am studying basic of angular.
I have a Django REST API running locally at -
http://127.0.0.1:8000/view/websyellow/
Now I want to make a normal post service from angular. Service is working fine on GET operation, but for POST it is giving an error -
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).
I am using Mozilla.
Service code -
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)
};
}
Component ts file -
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);
})
}
}
Component HTML File -
<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>
But if I use any server link it works correctly like any third party REST API.
How can I solve this problem.
It's a security feature.
You either use Angular Proxy, or add CORS headers to API.