node.js - 无法在我的本地主机之外的外部 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?
谢谢!:)
解决方案
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.
推荐阅读
- swift - 安装任何新 pod 时出现退出代码错误
- asp.net - M2Mqtt 连接失败
- vba - 如何使用 VBA 获取 Windows 文件类型
- internet-explorer - 包含本地包的 Vue-cli 项目在 ie 上显示错误
- javascript - 使用自定义事件扩展 jQuery 的 .on() 方法
- python - 无论我使用什么类型的激活函数,keras 卷积神经网络都在预测全零
- git - Git不会忽略具有字母数字模式的目录
- google-cast - 自动化 Chrome Cast 环境模式设置或 Google 相册内容
- java - 如何通过 Java 将字节数组插入 SQL?
- c - 任何人都可以在下面的 DAC 场景中帮助我吗