Superagent and create-react-app error, Module not found - reactjs

I am trying to use superagent with the create-react-app bootstrapper. I get the error:
Error in ./src/ToDoApp.js
Module not found: [CaseSensitivePathsPlugin] node_modules\superagent\lib\client.js does not match the corresponding path on disk - File does not exist.
I am importing the modules:
import request from 'superagent';
import noCache from 'superagent-no-cache';
I am using my request.get in ComponentDidMount
componentDidMount(){
request.get(this.apiUrl)
.use(noCache)
.end(function _requestCallback() {
// this.setState({data:res.data});
console.log('gotit');
});
}
Any ideas?

Edit:
An idea: install a newer version of both modules and try again

Related

I'm unable to load #apollo/client on a React Native Expo app

I'm trying to load #apollo/client on a React Native Expo app.
And I get this error:
While trying to resolve module #apollo/client from file /Users/andrepena/git/anglio-mobile-rn/screens/dictionary/index.tsx, the package /Users/andrepena/git/anglio-mobile-rn/node_modules/#apollo/client/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/andrepena/git/anglio-mobile-rn/node_modules/#apollo/client/main.cjs. Indeed, none of these files exist
Then I searched Stackoverflow and someone said I should add this to my metro.config.json
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;
But now, all imports from #apollo/client simply return undefined.
Example:
import { ApolloClient, InMemoryCache } from "#apollo/client";
console.log(ApolloClient); // undefined
console.log(InMemoryCache); // undefined
In fact, #apollo/client is exporting this object:
Object {
"default": 17,
}
Any suggestion?
This metro.config.js worked for me: (remember to install #expo/metro-config)
const { getDefaultConfig } = require('#expo/metro-config');
const config = getDefaultConfig(__dirname, {
// Initialize in exotic mode.
// If you want to preserve `react-native` resolver main field, and omit cjs support, then leave this undefined
// and skip setting the `EXPO_USE_EXOTIC` environment variable.
mode: 'exotic',
});
module.exports = config;
The exotic thing makes Metro to be able to find the weird cjs module that #apollo/client exports

Using Playfab SDK with ReactJS?

I am trying to use Playfab SDK on my React project, but no success yet..
I can't find well explained documentation for it.
created a react app with:
npx create-react-app playfabtest
installing PlayFab SDK for nodejs:
npm install playfab-sdk
NOTE: ( there is another SDK for JavaScript (npm install playfab-web-sdk), but I am assuming that for a react app, the nodes is the correct one ?)
The documentation for those SDK
Modified the App.js file on the project with this code:
(tried in many ways actually, I put the last one tried that didn't work neither).
App.js:
// import { PlayFabClient } from './playfab-sdk/Scripts/PlayFab/PlayFabClient';
// var PlayFabClient = require('./PlayFabSdk/Scripts/PlayFab/PlayFabClient.js')
function App() {
const PlayFabClient = require('./PlayFabSdk/Scripts/PlayFab/PlayFabClient.js');
PlayFabClient.settings.titleId = '';
PlayFabClient.settings.developerSecretKey = '';
PlayFabClient.GetTitleData({ Keys: ['Sample'] }, function (error, result) {
if (error) {
console.log('Got an error: ', error);
return;
}
console.log('Reply: ', result);
});
return ...
}
After that, if I run : npm start
get this error :
error:
Compiled with problems:
ERROR in ./src/PlayFabSdk/Scripts/PlayFab/PlayFab.js 4:10-24
Module not found: Error: Can't resolve 'url' in 'D:\Github\playfabtest\src\PlayFabSdk\Scripts\PlayFab'
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: { "url": require.resolve("url/") }'
- install 'url' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "url": false }
ERROR in ./src/PlayFabSdk/Scripts/PlayFab/PlayFab.js 6:12-28
Module not found: Error: Can't resolve 'https' in 'D:\Github\playfabtest\src\PlayFabSdk\Scripts\PlayFab'
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 }
Would be very helpful if can explain how to make PlayfabSDK run well on a react app.
Thanks a lot!
In the context of Create React App, you need to use ES6 style import statement instead of require to import the playfab-sdk NPM package into your project. Also you need to set the settings on the PlayFab object instead of the PlayFabClient.
Example:
import { useEffect, useState } from 'react';
import { PlayFab, PlayFabClient } from 'playfab-sdk'
PlayFab.settings.titleId = process.env.REACT_APP_PLAYFAB_TITLE_ID || ''
PlayFab.settings.developerSecretKey = process.env.REACT_APP_PLAYFAB_DEVELOPER_SECRET_KEY
// continue with component implementation
const App {
// get title data
PlayFabClient.GetTitleData(...)
// etc...
}
export default App

React Uncaught ReferenceError: Buffer is not defined

I created a React project by running npx create-react-app my-app
I installed mqtt-react-hooks
I added the App script
import { Connector } from 'mqtt-react-hooks';
import Status from './Status';
function App() {
return (
<Connector
brokerUrl="mqtt://127.0.0.1:80/"
parserMethod={(msg) => msg} // msg is Buffer
>
<Status />
</Connector>
);
}
export default App;
I get this error in the console
As mentioned in answers here please also consider the following:
npm install --save buffer
import {Buffer} from 'buffer';
It won't help in case of external library dependency but might save you from reverting other libraries in case of using Buffer in code directly.
I had this problem too.
Recently I create a new version of react app and when I used mqtt.js ( not mqtt-react-hooks ) this bad Error was shown!!!
I found out Webpack version 5 does not support Buffer and so on.
Webpack 5 removes Buffer (see this info), effectively breaking MQTT library since it has explicit usages of it in the code.
so I downgrade to Webpack 4 and it's work.
if you don't know how to do that, this link might be helpful.
How to downgrade version of Webpack?.
To me downgrading react-scripts to version 4.0.3 fixed the problem. It is not a proper fix but its something...
In my case I needed to do the following also:
In package.json use react-script 4.0.3
Remove package-lock.json
remove node_modules folder
run npm install
After all this everything seems to be working fine.
In Webpack version 5, Webpack no longer automatically polyfill's Node.js API's if they are not natively supported anymore. The browser environment does not support Buffer natively, therefore we now need to add a third party Buffer package and point Node.js to it in the Webpack config. See how to polyfill buffer with webpack 5.
Use this on the page or function where you get an error:
window.Buffer = window.Buffer || require("buffer").Buffer;
for me what worked was:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import path from 'path'
import inject from '#rollup/plugin-inject'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': path.resolve(__dirname, 'src'),
}
},
build: {
rollupOptions: {
plugins: [inject({ Buffer: ['buffer', 'Buffer'] })],
},
},
})
reply to this comment:
https://github.com/vitejs/vite/discussions/2785#discussioncomment-1452855
the only solution that worked for me was this:
npm add node-stdlib-browser
npm add -D vite-plugin-node-stdlib-browser
and then:
// vite.config.js
import { defineConfig } from 'vite'
import nodePolyfills from 'vite-plugin-node-stdlib-browser'
export default defineConfig({
// other options
plugins: [nodePolyfills()]
})

Module not found: Error: Can't resolve 'zlib'

I am trying to migrate a CRA react application to NX, following steps on the official site
When I hit nx serve
I am facing the following error:
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/png-js/dist/png-js.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\png-js\dist'
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/pdfkit/dist/pdfkit.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\pdfkit\dist'
Knowing that: before I start migration my project worked fine.
npm version: 6.14.11
node version: 14.16.0
I've tried to hit npm install zlib yet I get
Cannot find module './zlib_bindings'
For some reason, VSCode inserted import e from 'express' at the top of my file in react
import { response } from 'express';
I delete the above import line and then the problem is resolved, all the errors are gone after the above change.
It's about Webpack 5 and its default config you use for React app. I followed an advice from here: https://github.com/nrwl/nx/issues/4817#issuecomment-824316899 and React NX docs for how to use custom webpack config.
Create a custom webpack config, say, in /apps/myapp/webpack.config.js and reference it in workspace.json instead of "webpackConfig": "#nrwl/react/plugins/webpack". It should be "webpackConfig": "apps/myapp/webpack.config.js".
Content for webpack.config.js:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
node: undefined
};
};
So, this config change makes webpack correctly understand what polyfills are needed.
Alternatively, you can do the following:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
stream: require.resolve('stream-browserify'),
zlib: require.resolve('browserify-zlib'),
}
}
};
};
For me it was the code:
import { response } from 'express'
This was entered automatically by VSCode at the beginning of the file.
Deleting it solved the problem.
In my case was because I tried to type 'Text' and suddenly, the autocomplete added me this line on top:
import { text } from 'express';
Just deleted it and it worked fine.
Go Search Icon in VSCode search "express" you may get things like
import { text } from 'express'
import { Router } from 'express'
import { X,Y,Z } from 'express'
delete this line your app will work fine

React Js require 'fs'

I have
import fs from 'fs'
and in my package.json I have
Then I run the command
> npm i fs
> fs#0.0.2 node_modules/fs
next in my React store I import 'fs' module
import fs from 'fs'
However when I try to use fs
I don't see methods except for constructor and a few other __methods. I don't see the method createReadStream or any other file manipulation methods.
Does anybody know what is wrong? (using Webpack) and can give more information upon request, but I am getting this far...
ps: why is it that I can npm i fs --save when I read on other posts that I do not have to do that (using node 5.5.0)
import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from 'superagent-bluebird-promise'
import fs from 'fs'
var ImageStore = Reflux.createStore({
init(){
.
.
.
},
decryptImage(file) {
var reader = new FileReader();
var info = {}
reader.onload = (output) => {
debugger
request.post("https://camfind.p.mashape.com/image_requests")
.set("X-Mashape-Key", "KEY")
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json")
.send({'focus': { 'x': 480}})
.send({'focus': { 'y': 640}})
.send({'image_request': {'altitude': 27.912109375}})
.send({'image_request': {'language': "en"}})
.send({'image_request': {'latitude': 35.8714220766008}})
.send({'image_request': {'locale' : "en_US"}})
.send({'image_request': {'longitude': 14.3583203002251}})
.send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
.then(function (result) {
console.log(result.status, result.headers, result.body);
this.info = result
},
function(error) {
console.log(error);
})
}
reader.readAsDataURL(file);
return info
},
.
.
.
.
})
In create-react-app they have stubbed out 'fs'. You cannot import it.
They did this because fs is a node core module.
You'll have to find another solution to that problem. See this ticket.
It's possible this might be an environment issue. It's not possible for the browser to interpret and run some Node server-side modules like fs.
The solution is to run the fs methods in a Node environment (server-side) or to find a package which offers the same functionality but written for the browser.
It's discussed in this question...
Module not found: Error: Cannot resolve module 'fs'
And this question...
Use fs module in React.js,node.js, webpack, babel,express
npm i babel-plugin-preval
Though browser does not allow accessing file system during runtime, You can use prevail in React to read content from file system into memory during build time
like so
// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);

Resources