首页 > 解决方案 > 无法在我的本地主机之外的外部 URL 上发出请求

问题描述

通过“ https://www.google.com/ ”进行 GET 时出现此错误。

无法加载https://www.google.com/:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“ http://localhost:4200 ”。响应具有 HTTP 状态代码 405。

在服务器端,我使用 cors:

server.use(cors({
origin: '*',
credentials: true
}));

server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
Content-Type, Accept");
next();
});

server.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});

在客户端,我有一个 cookieService:

getCookies(URL) {
const headers = new Headers();
**headers.append('Access-Control-Allow-Origin', '*');**
return this.http.get(URL, { headers: headers }).map(res => res.json());
}

在一个角度组件上,我称之为这个函数:

searchCookies() {
this.cookieService.getCookies('https://www.google.com').subscribe();
}

有没有办法将此标头添加到 GET 响应中?还是有其他方法可以访问外部 URL,例如https://www.google.com

谢谢!:)

标签: node.jsheader

解决方案


CORS headers, which you are adding to localhost via your server response, do not work for google - the whole idea of CORS is that the 3rd party server (in this case https://google.com) can defend itself from Cross Origin Resource Sharing.

TL;DR - https://google.com doesn't allow localhost to access the website. If you want to scrape the website - you'd have to access it from node.js itself, rather than client-side JS.


推荐阅读