Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: this.opts.request is not a function when running client in Node.js; reopen issue #1191 #2415

Closed
jt0in3e opened this issue May 30, 2022 · 38 comments · Fixed by #2414 or #2719

Comments

@jt0in3e
Copy link

jt0in3e commented May 30, 2022

I would like to reopen the issue #1191 since there is a similar error.
I've installed matrix-sdk-js using Node.js v16.15.0 and initiated client as per example. Received TypeError: this.opts.request is not a function. Also tried with nodejs v12, import or require of SDK, using async ... await function, but the same issue.
any ideas?

Originally posted by @jt0in3e in #1191 (comment)

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

@jt0in3e please provide an actual snippet and error

image

@jt0in3e
Copy link
Author

jt0in3e commented May 30, 2022

@t3chguy

OS - linux (VoidLinux, 5.15.41_1)
node.js -> v16.5.0
npm/v.8.5.5, yarn/v.1.22.18

steps to reproduce:

  • mkdir "matrix-node-client" && cd
  • yarn init
  • yarn add matrix-sdk-js
  • touch index.js && vim index.js
    code snippet:
const sdk = require("matrix-js-sdk");

const client = sdk.createClient({
  baseUrl: "https://matrix.org",
  accessToken: "st_x.x.x.x.x.x.x.x.x.x.x",
  userId: "@yyyyyyyyyyyy:matrix.org"
});

client.startClient();
  • node index.js

ERROR ->

Getting saved sync token...
Getting push rules...
Got saved sync token
Getting saved sync...
Getting push rules failed TypeError: this.opts.request is not a function
    at MatrixHttpApi.doRequest (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/http-api.js:731:23)
    at MatrixHttpApi.requestOtherUrl (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/http-api.js:610:17)
    at MatrixHttpApi.request (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/http-api.js:566:17)
    at MatrixHttpApi.authedRequest (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/http-api.js:515:33)
    at MatrixClient.getPushRules (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/client.js:7099:22)
    at getPushRules (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/sync.js:523:37)
    at SyncApi.sync (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/sync.js:683:7)
    at MatrixClient.startClient (/home/user/matrix-node-client/node_modules/matrix-js-sdk/lib/client.js:470:18)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
Waiting for saved sync before retrying push rules...
Got reply from saved sync, exists? false
  • running without client.startClient() and with console.log(client.http.opts.request) gives no Errors and this response (cut):
{
  get: [Function (anonymous)],
  head: [Function (anonymous)],
  options: [Function (anonymous)],
  post: [Function (anonymous)],
  put: [Function (anonymous)],
  patch: [Function (anonymous)],
  del: [Function (anonymous)],
  delete: [Function (anonymous)],
  jar: [Function (anonymous)],
  cookie: [Function (anonymous)],
  defaults: [Function (anonymous)],
  forever: [Function (anonymous)],
  Request: [Function: Request] {
    debug: undefined,
    defaultProxyHeaderWhiteList: [
      'accept',           'accept-charset',
      'accept-encoding',  'accept-language',
      'accept-ranges',    'cache-control',
      'content-encoding', 'content-language',
      'content-location', 'content-md5',
      'content-range',    'content-type',
      'connection',       'date',
      'expect',           'max-forwards',
      'pragma',           'referer',
      'te',               'user-agent',
      'via'
    ],
    defaultProxyHeaderExclusiveList: [ 'proxy-authorization' ]
  },
  initParams: [Function: initParams],
  debug: [Getter/Setter],
  default: [Function: request] {
    get: [Function (anonymous)],
    head: [Function (anonymous)],
    options: [Function (anonymous)],
    post: [Function (anonymous)],
    put: [Function (anonymous)],
    patch: [Function (anonymous)],
    del: [Function (anonymous)],
    delete: [Function (anonymous)],
    jar: [Function (anonymous)],
    cookie: [Function (anonymous)],
    defaults: [Function (anonymous)],
    forever: [Function (anonymous)],
    Request: [Function: Request] {
      debug: undefined,
      defaultProxyHeaderWhiteList: [Array],
      defaultProxyHeaderExclusiveList: [Array]
    },
    initParams: [Function: initParams],
    debug: [Getter/Setter]
  }
}

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

#2415 fixes this

@jt0in3e
Copy link
Author

jt0in3e commented May 30, 2022

#2415 fixes this

@t3chguy nope, doesn't work. I've tried the fix with no success. the same problem (

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

@jt0in3e how are you testing it?

v18.0.0
image

#2414
image

@reesericci
Copy link

I just ran into this same error

@reesericci
Copy link

import * as sdk from "matrix-js-sdk";

const client = sdk.createClient("https://matrix.org");

client.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
});


client.once('sync', function(state, prevState, res) {
    if(state === 'PREPARED') {
        console.log("prepared");
    } else {
        console.log(state);
        process.exit(1);
    }
});

await client.startClient({initialSyncLimit: 10});

Node.js v17.3.0

Logs:

Public Rooms: undefined
Getting saved sync token...
Getting push rules...
Got saved sync token
Getting saved sync...
Getting push rules failed TypeError: this.opts.request is not a function
    at MatrixHttpApi.doRequest (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/http-api.js:731:23)
    at MatrixHttpApi.requestOtherUrl (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/http-api.js:610:17)
    at MatrixHttpApi.request (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/http-api.js:566:17)
    at MatrixHttpApi.authedRequest (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/http-api.js:515:33)
    at MatrixClient.getPushRules (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/client.js:7099:22)
    at getPushRules (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/sync.js:523:37)
    at SyncApi.sync (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/sync.js:683:7)
    at MatrixClient.startClient (/var/home/reesericci/js/node/internet-fax-machine/node_modules/matrix-js-sdk/lib/client.js:470:18)
    at async file:///var/home/reesericci/js/node/internet-fax-machine/index.js:19:1
Waiting for saved sync before retrying push rules...
Got reply from saved sync, exists? false
ERROR

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

import * as sdk from "matrix-js-sdk"; How are you installing matrix-js-sdk from that PR here?

@reesericci
Copy link

I just did npm i -S matrix-js-sdk

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

@reesericci that'll be js-sdk v18.0.0 - not the changes in the PR.

@reesericci
Copy link

So then how do I install the fix? I'd like to continue using NPM if possible

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

Either wait for the next release or install it via a github dependency https://www.pluralsight.com/guides/install-npm-packages-from-gitgithub

@reesericci
Copy link

What's the timeline for the next release?

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

Next tuesday but the fix caused other issues downstream so has to be backed out. https://github.com/matrix-org/matrix-react-sdk/runs/6656911557?check_suite_focus=true

@t3chguy t3chguy reopened this May 30, 2022
@reesericci
Copy link

I guess I'll wait for the release if the patch is causing issues.

Thanks!

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

You can workaround it using

const matrixcs = require("matrix-js-sdk/lib/matrix");
const request = require("request");
matrixcs.request(request);

image

@reesericci
Copy link

Will do - thanks for the workaround!

@jt0in3e
Copy link
Author

jt0in3e commented May 30, 2022

@t3chguy I see you reverted back changes. I've tried workarond and it works. Do I need to keep this workarond persistent?

@t3chguy
Copy link
Member

t3chguy commented May 30, 2022

@jt0in3e see #2415 (comment) for why the changes were reverted

@jt0in3e
Copy link
Author

jt0in3e commented May 31, 2022

@t3chguy ok, will stay with workaround for now, maybe smth will change in the future. Thank you for your help

@jt0in3e jt0in3e closed this as completed May 31, 2022
@reesericci
Copy link

Why is this issue closed? A workaround is not a fix, this issue should stay open until a real fix is merged and validated.

@t3chguy t3chguy reopened this May 31, 2022
@jt0in3e
Copy link
Author

jt0in3e commented May 31, 2022

Why is this issue closed? A workaround is not a fix, this issue should stay open until a real fix is merged and validated.

accidentally clicked on "close with comment" o_0

@reesericci
Copy link

The workaround isn't working for me when I use ESM because request only supports commonjs.

code:

import * as sdk from "matrix-js-sdk";
import matrixcs from "matrix-js-sdk";
import request from "request"

matrixcs.request(request)

// ...

error:

rollup v2.75.3
bundles src/index.ts → dist/bundle.js...
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
matrix-js-sdk (imported by src/index.ts)
[!] Error: 'default' is not exported by node_modules/request/index.js, imported by src/index.ts
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
src/index.ts (3:7)
1: import * as sdk from "matrix-js-sdk";
2: import matrixcs from "matrix-js-sdk";
3: import request from "request";
          ^
4: matrixcs.request(request);
5: const client = sdk.createClient({
Error: 'default' is not exported by node_modules/request/index.js, imported by src/index.ts
    at error (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:198:30)
    at Module.error (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:12723:16)
    at Module.traceVariable (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:13082:29)
    at ModuleScope.findVariable (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:11726:39)
    at Identifier.bind (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:8156:40)
    at CallExpression.bind (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:5360:73)
    at CallExpression.bind (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:9128:15)
    at ExpressionStatement.bind (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:5364:23)
    at Program.bind (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:5360:73)
    at Module.bindReferences (/var/home/reesericci/js/node/internet-fax-machine/node_modules/rollup/dist/shared/rollup.js:12719:18)

I'm using typescript with es2022 modules and es2020 target

su-ex added a commit to SchildiChat/matrix-js-sdk that referenced this issue Jun 7, 2022
* Convert `getLocalAliases` to a stable API call ([\matrix-org#2402](matrix-org#2402)).
* Fix request, crypto, and bs58 imports ([\matrix-org#2414](matrix-org#2414)). Fixes matrix-org#2415.
* Update relations after every decryption attempt ([\matrix-org#2387](matrix-org#2387)). Fixes element-hq/element-web#22258. Contributed by @weeman1337.
* Fix degraded mode for the IDBStore and test it ([\matrix-org#2400](matrix-org#2400)). Fixes matrix-org/element-web-rageshakes#13170.
* Don't cancel SAS verifications if `ready` is received after `start` ([\matrix-org#2250](matrix-org#2250)).
* Prevent overlapping sync accumulator persists ([\matrix-org#2392](matrix-org#2392)). Fixes vector-im/element-web#21541.
* Fix behaviour of isRelation with relation m.replace for state events ([\matrix-org#2389](matrix-org#2389)). Fixes element-hq/element-web#22280.
* Fixes matrix-org#2384 ([\matrix-org#2385](matrix-org#2385)). Fixes undefined/matrix-js-sdk#2384. Contributed by @schmop.
* Ensure rooms are recalculated on re-invites ([\matrix-org#2374](matrix-org#2374)). Fixes element-hq/element-web#22106.
@EgeKaanGurkan
Copy link

Has any fix to this issue been committed? I am getting the same error while trying to register a user.

@reesericci
Copy link

reesericci commented Jun 18, 2022

Is there any way to open a bounty on this issue? I'd be glad to throw some money your way if it meant that a fix would arrive.

@andreidiaconescu
Copy link

#2415 fixes this

PR 2415 seems to not exist ?
is there a fix for this issue, or is the js SDK not usable at the moment ?

thank you,
Andrei

@MTRNord
Copy link
Contributor

MTRNord commented Jul 14, 2022

Getting this with a vitejs + preact + typescript setup as well when I try to login with password :/

@dcolley
Copy link

dcolley commented Jul 19, 2022

It was not clear whether you're in ts or js?
Anyway, using the responses from this post I am able to get this working on node v16.15.0

test.js

import * as sdk from 'matrix-js-sdk'
import matrixcs from 'matrix-js-sdk'
import request from 'request'
matrixcs.request(request)

console.log('starting...')

const client = sdk.createClient('https://matrix.org')
console.log('we have a client...')

client.login('m.login.password', {
    'user': '@metaspan:matrix.org',
    'password': '123456'
})
  .then((response) => {
      console.log(response)
      console.log(response.access_token)
  })
  .catch(err => {
      console.warn('caught an error!')
      console.error(err)
  })
  .finally(() => {
      console.log('we\'re done')
  })

console.debug('all done...')

produces

node test.js
starting...
we have a client...
all done...
{
  user_id: '@metaspan:matrix.org',
  access_token: 'syt_asdfasdf_asdfasdf_3b2yjA',
  home_server: 'matrix.org',
  device_id: 'asdfJJasdf',
  well_known: { 'm.homeserver': { base_url: 'https://matrix-client.matrix.org/' } }
}
syt_asdfasdf_asdfasdf_3b2yjA
we're done

@reesericci
Copy link

reesericci commented Jul 19, 2022

I was using TypeScript + Rollup.js + ESM

@tearfulnumpty
Copy link

Is it possible there is another workaround that doesn't use the request package? I understand that work is being done to move from request to fetch but I'm just not sure how long that will take, especially since the idea of moving away from request has been around since 2018.

I don't mean to be impatient or ungrateful for the work put into projects like this, I'm just hoping to find a more immediate solution to the OP problem described here without relying on requests, if it's possible.

@t3chguy
Copy link
Member

t3chguy commented Aug 9, 2022

Given you can pass any method which fulfils the contract, you could write a request shim based on fetch, using async-await before calling the callback function.

@reesericci
Copy link

I can't use the SDK at the moment because of this - this needs to be top priority

@universalappfactory
Copy link

Hi, I had the same issue.

Setting ICreateClientOpts.request did the trick for me.

`
const request = require("request");

// ...

const client = sdk.createClient({
baseUrl: 'https://matrix.org',
request: request
})

// ...
`

@tearfulnumpty
Copy link

But you're still using the requests package, which doesn't really help the rest of things out. This package has been deprecated for about 2 years already - this sdk really needs to move away from it altogether.

@universalappfactory
Copy link

universalappfactory commented Aug 23, 2022

Yes that's a good point.

But you can also use another library as workaround as long as #801 is ongoing I think.

@ghost stated an axios example there.

I'm still in an dev setup and tried a little modified version just as an example if anyone is interested in.

`const request = async function(opts, callback) {
opts.url = opts.uri;
opts.data = opts.body;

if (opts.method === 'GET' && opts.useQuerystring) {      
  opts.params = opts.qs
} else {      
  if (opts._matrix_opts.accessToken) {        
    opts.headers['Authorization'] = `Bearer ${opts._matrix_opts.accessToken}`
  }
}

const response = await axios.request(opts)
callback(null, response, JSON.stringify(response.data));  

}`

@andreidiaconescu
Copy link

any update on this issue please ?
this seems really blocking: usage of the JS SDK is blocked by this error .

@t3chguy
Copy link
Member

t3chguy commented Sep 12, 2022

@andreidiaconescu there is a workaround above by passing request.

@sushantdhiman
Copy link

Following works for me :-

import * as sdk from "matrix-js-sdk";
import request from "request";

const matrixClient = sdk.createClient({
  baseUrl: "https://matrix.org",
  request,
});

const starting = matrixClient.startClient();

export async function notifications() {
  await starting;

  await matrixClient.sendMessage(<ROOM_ID>, {
    body: message,
    msgtype: "m.text",
  });
}

petemoore added a commit to taskcluster/taskcluster that referenced this issue Oct 18, 2022
su-ex added a commit to SchildiChat/matrix-js-sdk that referenced this issue Oct 29, 2022
* Changes the `uploadContent` API, kills off `request` and `browser-request` in favour of `fetch`, removed callback support on a lot of the methods, adds a lot of tests. ([\matrix-org#2719](matrix-org#2719)). Fixes matrix-org#2415 and matrix-org#801.
* Remove deprecated `m.room.aliases` references ([\matrix-org#2759](matrix-org#2759)). Fixes element-hq/element-web#12680.
* Remove node-specific crypto bits, use Node 16's WebCrypto ([\matrix-org#2762](matrix-org#2762)). Fixes matrix-org#2760.
* Export types for MatrixEvent and Room emitted events, and make event handler map types stricter ([\matrix-org#2750](matrix-org#2750)). Contributed by @stas-demydiuk.
* Use even more stable calls to `/room_keys` ([\matrix-org#2746](matrix-org#2746)).
* Upgrade to Olm 3.2.13 which has been repackaged to support Node 18 ([\matrix-org#2744](matrix-org#2744)).
* Fix `power_level_content_override` type ([\matrix-org#2741](matrix-org#2741)).
* Add custom notification handling for MSC3401 call events  ([\matrix-org#2720](matrix-org#2720)).
* Add support for unread thread notifications ([\matrix-org#2726](matrix-org#2726)).
* Load Thread List with server-side assistance (MSC3856) ([\matrix-org#2602](matrix-org#2602)).
* Use stable calls to `/room_keys` ([\matrix-org#2729](matrix-org#2729)). Fixes element-hq/element-web#22839.
* Fix POST data not being passed for registerWithIdentityServer ([\matrix-org#2769](matrix-org#2769)). Fixes matrix-org/element-web-rageshakes#16206.
* Fix IdentityPrefix.V2 containing spurious `/api` ([\matrix-org#2761](matrix-org#2761)). Fixes element-hq/element-web#23505.
* Always send back an httpStatus property if one is known ([\matrix-org#2753](matrix-org#2753)).
* Check for AbortError, not any generic connection error, to avoid tightlooping ([\matrix-org#2752](matrix-org#2752)).
* Correct the dir parameter of MSC3715 ([\matrix-org#2745](matrix-org#2745)). Contributed by @dhenneke.
* Fix sync init when thread unread notif is not supported ([\matrix-org#2739](matrix-org#2739)). Fixes element-hq/element-web#23435.
* Use the correct sender key when checking shared secret ([\matrix-org#2730](matrix-org#2730)). Fixes element-hq/element-web#23374.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
10 participants