Cannot import HTTPS in React application [duplicate] - node.js

This question already has answers here:
How to Polyfill node core modules in webpack 5
(32 answers)
Closed 9 months ago.
I have a React application and i've been trying to make axios requests to an API ignoring SSL verification like this:
const https = require('https');
const axios = require('axios');
const agent = new https.Agent({
rejectUnauthorized: false
});
axios.get('https://example.com', { httpsAgent: agent });
But I have this error:
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'
- install 'https-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "https": false }
The React app was created using npm create-react-app.
I've tried to install https via npm install https, and to install https-browserify, but got the same error.
I'm using nodejs v16.13.2 and react 18.1.0
Why am I getting this error?.
Thanks in advance.

first please check if your website is working on HTTPS or HTTP if your site is running on HTTP then you might add SSL for request handling or if your site is running on HTTPS then it's coming because the server-side is blocking your request you can use CORS package in server-side for allowing non secure origin
it worked for me.

Related

Module not found Error: Can't resolve 'http' in a reactapp using authorize.net

I am trying to run npm run build on a react app which uses the charge-credit-card.js from Authorize.net node.js SDK inside a react app (Hyva React Checkout) like so:
import { chargeCreditCard } from '../api/charge-credit-card';
However I am getting this kind of error in the console while running npm run build on the react app:
Module not found: Error: Can't resolve 'http' in '/var/www/html/app/code/MyVendorName/Checkout/reactapp/node_modules/authorizenet/node_modules/winston/lib/winston/transports'
Did you mean './http'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules, /var/www/html/app/code/MyVendorName/Checkout/reactapp/node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
- install 'stream-http'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "http": false }
Not entirely sure why this is happening and how it can be mitigated.
Any help is highly appreciated.

Using ipcRenderer in Angular 15 + Electron 22 project causes building errors

I am trying to use ipcRenderer in an Angular service. My project will only work in an Electron environment. If I try to use the standard builder, I get the following error:
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
If I use the esbuild builder, this is what I get:
X [ERROR] Could not resolve "fs"
node_modules/electron/index.js:1:19:
1 │ const fs = require('fs');
╵ ~~~~
The package "fs" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
I tried to put
"platform: 'node'"
Both in tsconfig file and angular.json file, but it seems like it is not a valid option.
If I add this block to package.json:
"browser": {
"path": false,
"fs": false
}
Then I have the following error at runtime:
ERROR Error: Uncaught (in promise): ReferenceError: __dirname is not defined
Even though I haven't used __dirname anywhere in the browser code.
What should I do to make it work?
Electron has two separate processes - the render process, which runs in the bundled web browser (the ipcRenderer), and the main process, which runs in a node.js process.
As such, you can use core node.js modules in the main process, but not in the ipcRenderer since these modules (e.g. fs) are not available in the browser.
It sounds like you're trying to use fs in the renderer (your Angular app). That's not going to work.
If you want to, for example, read data from the file system and display it in the browser, you're going to have to use Electron's interprocess communications to have the Angular ask the main process to read the file, and then pass the content back to the renderer from the main process asynchronously.

Nestjs server does not serve socket.io client

I have a split app using nestjs on the server and an Angular app as the client. Setting up websockets with socket.io seemed pretty easy using the #nestjs/websockets module and on the client I used ngx-socket-io. I used this repo as basis. Now when I update the project's #nestjs/websockets dependency to the latest version I get
CORS errors and
an error that the client couldn't load the socket.io client js file
I expected CORS problems and after the update, I could fix them by adding
app.enableCors({
origin: 'http://localhost:4200',
credentials: true,
});
to my main.ts file, but I don't know why the client file is not served. With the version of the repo (5.7.x) there are neither CORS errors nor problems with serving the file.
I tried a couple of settings of #WebSocketGateway(), moving to a different port, setting serveClient (even though it should be true by default), but nothing seemed to work. Any advice?
thanks
In my case
I replaced
app.useWebSocketAdapter(new WsAdapter(app));
from
import { WsAdapter } from '#nestjs/platform-ws';
with
app.useWebSocketAdapter(new IoAdapter(app));
in main .ts from
import { IoAdapter } from '#nestjs/platform-socket.io';
Worked like a charm!
The problem was that nestjs did separate the lower level platform (socket.io, express, fastify, ...) from the nestjs modules. The websocket module requires to install an underlying platform, for socket.io
npm install --save #nestjs/platform-socket.io
To serve the socket.io client file it seems like there also needs to be an HTTP platform installed, for express
npm install --save #nestjs/platform-express
More info in the migration guide for v6.
I had the same problem. i was opening the client side of the application in the web-browser, but directly from my filesystem (i would double click on the file index.html next to the little dummy fake-front-end.js on my desktop for example...). It seems that the CORS problem would persist until i actually accessed the index.html through a proper server. So i created a route on my backend, to serve the index.html, and the fake-front-end.js.
There is a section about CORS on the socket.io officual documentation. And there is a section on the nestjs website, but both didnt really helped in my case.

"ReferenceError: WebSocket is not defined" when using RxJs WebSocketSubject and Angular Universal

I'm setting up an angular 6.x univeral project in order to leverage its SSR (Server-Side Rendering) capabilities. In my app, I'm using websocket communication using RxJs.
More specifically, I'm, using WebSocketSubject and webSocket in my angular universal 6.x project, which works fine on the browser platform. However, when running the node web server (that contains the SSR stuff (Server-Side Rendering)), an error is thrown:
ReferenceError: WebSocket is not defined
Example code:
// not actually code from the reproduction repo
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
const socket: WebSocketSubject<any> = webSocket('wss://echo.websocket.org');
socket.subscribe(msg => doSomething(msg));
Please note, that the error doesn't occur on the browser version of the app (i.e. ng serve won't throw the error), but only after compiling the SSR stuff and running the express web server. To reproduce the error, the builds have to be run first:
# install dependencies
npm install
# build angular bundles for browser and server platforms
npm run build:client-and-server-bundles
# build the webserver
npm run webpack:server
# start the webserver
npm run serve:ssr
# the app is now being served at http://localhost:8081/
# open it in the browser and the error will occur: 'ReferenceError: WebSocket is not defined'
I've also set up a reproduction repo.
Environment I'm using:
Runtime: Angular 6
RxJS version: 6.2.0, 6.2.1, 6.2.2 (tested all)
Edit 2018-08-02
I was able to address the problem more accurately. It seems, that this is also a webpack problem. Angular Universal creates a js bundle for running the angular app on the node server, but there is natively no websocket implementation on Node. Therefore, it has to be added manually as a dependency (npm package). I tried adding it to the js server bundle (const WebSocket = require('ws'); manually, which resolves the problem (i.e. ReferenceError disappears). However, when I add it to the TypeScript code that gets transcompiled into the js bundle later on, it won't work.
Further details
The webpack loader ts-loader is used for compiling TypeScript => JavaScript
The websocket depedency was added to the package.json: "ws": "^6.0.0"
Attempting to reference the ws dependency by adding const WebSocket = require('ws'); to the uncompiled TypeScript code won't resolve the issue. It would get compiled into var WebSocket = __webpack_require__(333); in the js output file, the dependency won't be able to be resolved.
Manually changing var WebSocket = __webpack_require__(333); => const WebSocket = require('ws'); in the compiled js file would resolve the issue, but of course it's a hack.
So, the questions are:
Can I "force" webpack to compile the dependency const WebSocket = require('ws'); => const WebSocket = require('ws'); (no changes)?
Or, would it might be a better solution, to register this dependency in the angular universal npm package and create a pull request?
The RxJS webSocket function can receive a WebSocket Constructor as an argument. This can be used to run webSocket in a non-browser/universal environment like this.
const WebSocketConstructor = WebSocket || require('ws')
const socket: WebSocketSubject<any> = webSocket({
url: 'wss://echo.websocket.org',
WebSocketCtor: WebSocketConstructor,
});
// OR...
import { WebSocket, ...otherStuff... } from 'ws';
import { webSocket, ...otherStuff... } from 'rxjs/webSocket';
const socket$ = webSocket({
url: 'wss://someplace.com',
WebSocketCtor: WebSocket,
});
All it takes is this:
// set WebSocket on global object
(global as any).WebSocket = require('ws');
And of course, we need the ws dependency as well in the package.json:
npm i ws -s
In nodeJS apps with ES6 or similar, you must use this:
global.WebSocket = require('ws')
For example:
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
global.WebSocket = require('ws'); // <-- FIX ALL ERRORS
const subject = webSocket('ws://...');
No more errors.
My first answer!! Cheers
I created a npm package using websockets.
To provide compatibility for server side js and browser js i use this code.
(Note: it is typescript)
if (typeof global !== 'undefined') {
(global as any).WebSocket = require('ws');
}
Like you mentioned, the browser already has a WebSocket in its global object window but node does not.
Since the browser does not have global, this simple check works well.
Compiled code:
if (typeof global !== 'undefined') {
global.WebSocket = require('ws');
}

Can I use node.js server modules in webpack?

Can we import all node.js modules in webpack and create a bundle.js? Example what if I use http module and webpack application and bundle it and run in browser?
main.js
var http = require('http');
var server = http.createServer(function (req, res) {
// send output
});
server.listen(8080);
When using Node's built-in libraries with Webpack, it will automatically import a browser-compatible version when available.
You can see the entire list and matching packages in this file.
For http, you'll end up with http-browserify instead. Not everything is supported, so creating a HTTP server will not work (as this isn't possible in a browser). You can still use http to do requests as shown in the documentation.

Resources