angular - 跨域请求被阻止:同源策略不允许读取远程资源
问题描述
我刚刚开始研究 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 一样正常工作。
我怎么解决这个问题。
解决方案
这是一项安全功能。
您要么使用Angular Proxy,要么将CORS 标头添加到 API。
推荐阅读
- json - 接受 POST WebHook 的 Vb.net 桌面应用程序
- javascript - 带有角度指令 ngIf 的 Animejs
- python - 使用包含路径的选项卡对图像进行分类
- php - 写入 CSV 文件时 PHP 变量为空
- mysql - Docker 容器无法连接到它的 mysql 服务器(访问被拒绝)
- android - 无法从 Firebase 获取 RemoteConfig 数据
- expo - Expo:如何以编程方式更改启动图像?
- vue.js - 在 Vuetify Vue 中添加自定义图标或徽标
- python - Fenics - as_tensor 错误:ufl.log.UFLException:组件和形状长度不匹配
- c# - 实时绘制 WPF 的 3D 模型