Request.js Browserify 无法正常工作

Request.js not working properly with Browserify

我目前正在构建一个 js chrome 扩展,为此,我需要从一些网站上抓取数据。

因此,基于 this SO question I found that I could achieve that using request with Browserify

我使用 npm 安装了两者并创建了一个 browserify.js 片段来创建我的 bundle.js 文件(因为权限原因 运行ning 终端命令不工作),所以我可以在客户端,我的浏览器中运行 Node js require

好的,所以我终于设法创建了 bundle.js 文件并尝试在我的本地服务器中 运行 它,但它一直给我 CORS 错误并且没有 return 期望的响应:

Fetch API cannot load https://somesite/index.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

一件奇怪的事情是,如果我使用 node:

直接从终端 运行 "unbundled" 文件
$ node myFileWithRequires.js

它按预期工作,return编辑了废弃的数据。

我做错了什么?如何使用 requestbrowserify 在客户端中抓取数据?

代码:

myBrowserifySnippet.js

var browserify = require('browserify');
var b = browserify();
b.add('myrequest.js');
const fs = require('fs');
const writable = fs.createWriteStream('bundle.js');
b.bundle().pipe(writable);

myFileWithRequires.js

var request = require('request');
request('http://www.google.com', function (error, response, body) {
    console.log('error:', error); // Print the error if one occurred
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body); // Print the HTML for the Google homepage.
      });

默认情况下,XHR 和 fetch 请求受 CORS 约束,这意味着它们无法访问其他域上的资源,除非这些域将 'origin'(当前页面的域)列入白名单。 request在浏览器中使用XHR,所以也被CORS绑定

在 Chrome 扩展中,它有点不同——您可以配置您的扩展,以便 CORS 不适用于某些域。请参阅 chrome 扩展文档中的 Requiesting cross-origin permissions

您需要在扩展中添加一个 permissions 字段 manifest.json:

{
  "permissions": [
    "http://www.google.com/"
  ]
}

如果您事先不确定要抓取哪个域,可以使用通配符:

{
  "permissions": [
    "http://*/",
    "https://*/"
  ]
}