How to make HTTP requests from Firefox extension

2019-09-01 02:20发布

问题:

I want to make HTTP requests from Firefox extension, so I decided to use third-party libraries request and cheerio for this purpose.

Unfortunately, when I import them via the following statements

var request = require('request');
var cheerio = require('cheerio');

it give me the following error when I run it via jpm run:

console.error: forwardme: Message: Module net is not found at resource://gre/modules/commonjs/net.js Stack: @resource://forwardme/node_modules/request/node_modules/tough-cookie/lib/cookie.js:32:11 @resource://forwardme/node_modules/request/lib/cookies.js:3:13 @resource://forwardme/node_modules/request/index.js:18:29 @resource://forwardme/index.js:21:15 run@resource://gre/modules/commonjs/sdk/addon/runner.js:145:19 startup/

Why? What am I doing wrong?

What is the easiest way to make HTTP GET and POST requests from Firefox addon?

回答1:

Core node modules are not available in SDK because it's not actually a node environment.

I recommend you browse MDN to see available APIs like Request.

Alternatively, you can make use of the fetch API which is the new kid on the block everyone is talking about these days. This of course needs a reference to a window object.